Laravel关系返回两次项目

时间:2017-09-16 13:22:10

标签: php laravel relational-database

我在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”一次(这应该是怎样的)

1 个答案:

答案 0 :(得分:0)

我使用contains()方法解决了我的问题 该功能现在看起来像这样:

public function getAllProducts()
{
    $products = $this->products;

    foreach ($this->children as $child) {
        foreach ($child->products as $product) {
            if (!$products->contains($product)) {
                $products[] = $product;
            }
        }
    }

    return $products;
}

但如果我不使用contains

,我仍然不知道为什么它会两次返回“shirt1”