2 回答

TA貢獻1936條經驗 獲得超7個贊
使用 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 關注
- 122 瀏覽
添加回答
舉報