【发布时间】:2017-09-16 13:22:10
【问题描述】:
我在 Laravel 5.5 中有分类和产品 每个产品都有一个类别,类别可以有父类别。我想在展示时获取某个类别的所有儿童产品。示例:衣服是一个类别,有衬衫、夹克等子类别,当单击衣服类别时,我想显示所有具有衬衫或夹克类别的产品。 这是我的 Category.php 模型:
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”。 “cloth1”和“cloth2”属于衣服类别,“shirt1”属于衬衫类别,这是衣服的子类别。因此,当我在衣服类别页面上时,我想显示所有产品(“cloth1”、“cloth2”和“shirt1”) 但在视图中
{{dd($category->getAllProducts())}}
返回“cloth1”、“cloth2”、“shirt1”、“shirt1”(它返回衬衫两次)。知道为什么以及如何解决这个问题吗?
编辑:当我在衣服类别上尝试 $category->products 时,它返回“cloth1”和“cloth2”,当我在衬衫类别上尝试时,它只返回一次“shirt1”(即应该怎样)
【问题讨论】:
-
$this->products和$this->children上缺少()是不是错字? -
没有。据我所知,laravel 关系是这样工作的,只有当函数不返回关系时才需要括号。
-
好吧,令人困惑,哈哈,这可能是因为
$products已经包含一个数组,您只需在循环$products[]中再次添加相同的值,也许将返回数组重命名为其他名称。在循环中尝试dd()ing 看看它在做什么。 -
@LawrenceCherone foreach 之前的数组包含当前的“衣服”类别“cloth1”和“cloth2”,foreach 将每个子项的每个产品添加到数组中
-
@LawrenceCherone 在提问之前我已经这样做了。我删除了foreach,让它只返回
$this->products,它只返回“cloth1”和“cloth2”。我也dd()ied 孩子们,它返回了“衬衫”,当我在“衬衫”上尝试$category->products时,它只返回了一次“衬衫1”,这是它应该做的
标签: php laravel relational-database