【发布时间】:2017-07-30 01:54:25
【问题描述】:
我有一个用户,他有很多商店,而一个商店有很多产品
现在我想知道,有没有一种方法可以为该用户获取所有产品的集合。
无需遍历他拥有的商店。
当前方法,返回带有产品的商店集合而不是产品集合
$products = \Auth::user()->shops()->with('products')->get();
【问题讨论】:
我有一个用户,他有很多商店,而一个商店有很多产品
现在我想知道,有没有一种方法可以为该用户获取所有产品的集合。
无需遍历他拥有的商店。
$products = \Auth::user()->shops()->with('products')->get();
【问题讨论】:
您需要定义一个HasManyThrough relation
class User extends Model
{
...
public function products()
{
return $this->hasManyThrough('App\Product', 'App\Shop');
}
...
}
【讨论】:
skus.*, shops .user_id from skus inner join shops on shops.id = skus.shop_id where shops.user_id = 2),哦,(SKU = PRODUCT)跨度>
您可以使用pluck方法从多个商店获取所有产品。
public function products()
{
return $this->shops->pluck('products');
}
public function shops()
{
return $this->belongsToMany(Shop::class);
}
($this 是您的用户模型的一个实例)
并且在您的商店模型上,您必须与产品有 Laravel 关系
public function products()
{
return $this->belongsToMany(Product::class);
}
【讨论】: