【问题标题】:Laravel relationship returns items twiceLaravel 关系两次返回项目
【发布时间】: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


【解决方案1】:

我使用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”@

【讨论】:

    猜你喜欢
    • 2018-11-05
    • 1970-01-01
    • 2020-07-31
    • 2014-08-21
    • 2016-06-21
    • 2019-10-09
    • 1970-01-01
    相关资源
    最近更新 更多