Php Laravel雄辩的ORM-通过另一个对象返回对象

Php Laravel雄辩的ORM-通过另一个对象返回对象,php,laravel,model,eloquent,relation,Php,Laravel,Model,Eloquent,Relation,我有3个模型:商店、产品和标签。商店与产品是一对多的关系,而产品与标签是多对多的关系 我想抓住每个商店所有独特的标签(因为许多产品可以有相同的标签) 我提出的解决方案之一是:。问题是我没有得到唯一的标签。有一种解决方案可以放置另一个foreach循环来遍历标记数组并比较标记对象中的id。我想优化一下,你认为什么是更好/更清洁的解决方案 class Shop extends Eloquent { ... public function getTagsAttribute() {

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

我想抓住每个商店所有独特的标签(因为许多产品可以有相同的标签)

我提出的解决方案之一是:。问题是我没有得到唯一的标签。有一种解决方案可以放置另一个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;
    }
}

也许你可以试试这个:

$tags = Tag::has('products')->get();
这将返回绑定到任何
产品
的所有
标记。如有必要,您也可以像这样使用
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;
}

@狼人的方法对你有用,但这里有一个技巧对所有关系都有用:

$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
属性,因为它是一个
归属关系
关系,但显然您并不依赖于此。

我正在尝试获取属于特定商店的唯一标签。。有一个伟大的工作之间的模式,非常感谢。这就是我一直在寻找的是的,值得注意的是:它执行额外的查询来获取这些标记。这是缺点,但它仍然是迄今为止实现您所需的最简单的解决方案。
$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