2 回答

TA贡献1936条经验 获得超6个赞
使用 whereHas 两次解决:
$products = Product::with('categories')->whereHas('categories',function($query){
$query->where('slug',request()->category);
})->whereHas('orders',function($query){
$query->where('orders.user_id',Auth::id());
})->get();

TA贡献1811条经验 获得超6个赞
基本上 Eloquent 模型不鼓励连接表来检索数据。它应该仅用于过滤结果(因此您需要使用删除其他表的字段->select('original_table.*'))
在这种情况下,您应该首先简单地检索categories。然后使用关系属性访问检索相关数据。
例如
$categories = Category::query()
->with('products')
->where('slug', request('category'))
->get();
$products = $categories->flatMap->products;
$pivots = $products->map->pivot;
- 2 回答
- 0 关注
- 98 浏览
添加回答
举报