我的问题本质上是这样的,我有一个间接引用模型使用相关模型的问题,就像'模型A'有很多'模型B'和'模型B'一样许多'模型C',所以基本上这将是'模型A'有许多'模型C',但我不知道如何使用hasMany来联系他们。Laravel雄辩的间接关系船使用hasMany
现在我的实际情况是我店里有很多产品类别,每个产品类别都有很多产品,所以Shop-> ProductCategory是使用hasMany相关的,以及ProductCategory->使用hasMany的产品,我想要关联商店和产品而不在产品表中创建新列以存储商店ID。
这里是我的模型
/* Models */
// Shop.php
<?php
class Shop extends Eloquent {
public function productCategories() {
return $this->hasMany('ProductCategory');
}
}
?>
//Product.php
<?php
class Product extends Eloquent {
public function productCategory() {
return $this->belongsTo('ProductCategory');
}
}
?>
//ProductCategory.php
<?php
class ProductCategory extends Eloquent {
public function shop() {
return $this->belongsTo('Shop');
}
public function products() {
return $this->hasMany('Product');
}
}
?>
在这种情况下,我将无法获得下店铺的所有产品,我将不得不遍历每个类别获得的所有产品。 而不是商店 - >产品,我将不得不编写一个循环来获取所有产品? –
检查答案中给出的热切加载链接,有一个例子,你可以循环。 –