我在Laravel 5.5中有类别和产品 每个产品都有一个类别和类别可以有父类别。我想在展示时获得一个类别的所有儿童产品。例如:衣服是一个cateogry,并有像衬衫,夹克等子类别,当我点击衣服类别时,我想显示所有具有衬衫或夹克类别的产品。 这里是我的Category.php型号:Laravel关系返回项目两次
public function children()
{
return $this->hasMany('App\Category', 'parent_id');
}
public function products()
{
return $this->hasMany('App\Product');
}
public function getAllProducts()
{
$products = $this->products;
foreach ($this->children as $child) {
foreach ($child->products as $product) {
$products[] = $product;
}
}
return $products;
}
在我来说,我有一个是 “cloth1”, “cloth2” 和 “shirt1” 三款产品。 “布料1”和“布料2”属于衣服类别,“衬衫1”属于衣服子类别的衬衫类别。所以,当我的衣服分类页面上我想告诉所有的产品(“cloth1”,“cloth2”和“shirt1”) 但在视图
{{dd($category->getAllProducts())}}
返回“cloth1”,“cloth2” “shirt1”,“shirt1”(它将衬衫返回两次)。任何想法为什么以及如何解决这个问题?
编辑:当我尝试$category->products
的衣服类别,它返回“cloth1”和“cloth2”,当我尝试它放在衬衫类别,它返回“shirt1”只有一次(这是应该的)
是否在'$ this-> products'和$ $ this-> children'上缺少'()'的拼写错误? –
不可以。就我所知,laravel关系是这样工作的,括号只在函数不返回关系时才需要。 – TheAngelM97
好吧,混淆哈哈,所以可能是因为'$ products'已经包含一个数组,你只需在循环'$ products []'中再次添加相同的值,也许可以将返回数组重命名为其他值。试着在循环中使用'dd()来看看它在做什么。 –