HasMany关系作为合并集合

时间:2016-03-06 23:35:12

标签: laravel laravel-5 eloquent

我有一个商家模型,这个商家模型有很多类别,每个类别都有很多产品。

现在,对于我的产品索引,我想列出给定商家的所有产品。

$categories = Category::where('merchant_id', 1);

foreach ($categories as $category) {
    $products[] = Product::where('category_id', $category->id);
}

此代码将为我提供一系列商品的所有商品集合,ID为1。

如何组合这些集合,以便将它们传递给我的视图?

return view('products.index', compact('products'));

1 个答案:

答案 0 :(得分:1)

您需要的是您的Merchent与您认为的产品之间的HasManyThrough关系:

class Merchant extends Model
{
    /**
     * Get all of the products for the merchant.
     */
    public function products()
    {
        return $this->hasManyThrough('App\Product', 'App\Category');
    }
}

然后,您应该能够使用$merchant->products

检索给定商家的所有产品

如果您需要更多信息,请参阅以下文档: https://laravel.com/docs/5.2/eloquent-relationships#has-many-through

祝你好运,我希望它有所帮助!

相关问题