【问题标题】:Laravel Eloquent ORM - return objects thru another objectsLaravel Eloquent ORM - 通过另一个对象返回对象
【发布时间】:2014-09-02 18:36:03
【问题描述】:

我有 3 个模型:商店、产品和标签。 Shop 和 Products 是一对多的关系,Products to Tags 是多对多的关系。

我想为每个 Shop 获取所有唯一标签(因为许多产品可以有相同的标签)。

class Shop extends Eloquent {

    public function products() {
        return $this->hasMany('Product');
    }
}


class Product extends Eloquent {

    public function shop() {
        return $this->belongsTo('Shop');
    }

    public function tags() {
        return $this->belongsToMany('Tag');
    }
}

class Tag extends Eloquent {

    public function products() {
        return $this->belongsToMany('Product');
    }
}

我想出的解决方案之一如下。问题是我没有得到唯一的标签。有一个解决方案可以放置另一个 foreach 循环来遍历标签数组并比较标签对象中的 id。我想稍微优化一下,您认为更好/更清洁的解决方案是什么?

class Shop extends Eloquent {

    ...

    public function getTagsAttribute() {
        $tags = array();
        foreach($this->products as $product)
        {
            foreach ($product->tags as $tag)
            {
                $tags[] = $tag;
            }
        }

        return $tags;
    }
}

【问题讨论】:

    标签: php laravel model eloquent relation


    【解决方案1】:

    @WereWolf 的方法适用于您,但这里有一个适用于所有关系的技巧:

    $shop = Shop::with(['products.tags' => function ($q) use (&$tags) {
      $tags = $q->get()->unique();
    }])->find($someId);
    
    // then:
    $tags; // collection of unique tags related to your shop through the products
    

    请注意,每个 $tags 都将具有 pivot 属性,因为它是 belongsToMany 关系,但显然您不依赖它。

    【讨论】:

    • 是的,只是值得注意:它执行额外的查询来获取这些标签。这是不利的一面,但它仍然是迄今为止实现您需要的最简单的解决方案。
    【解决方案2】:

    也许你可以试试这个:

    $tags = Tag::has('products')->get();
    

    这将返回绑定到任何Product 的所有Tags。如有必要,你也可以使用distinct,像这样,但我认为这种情况下没有必要:

    $tags = Tag::has('products')->distinct()->get();
    

    更新:那你可以试试这样的:

    public function getTagsAttribute()
    {
        $shopId = $this->id;
    
        $tags = Tag::whereHas('products', function($query) use($shopId) {
            $query->where('products.shop_id', $shopId);
        })->get();
    
        return $tags;
    }
    

    【讨论】:

    • 我正在尝试获取属于特定商店的唯一标签.. 之间有一个模型
    • 干得好,非常感谢。这就是我一直在寻找的东西
    猜你喜欢
    • 2014-12-14
    • 2013-05-26
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 2013-05-20
    • 2018-07-02
    • 1970-01-01
    相关资源
    最近更新 更多