我有這個搜索查詢
$products = Product::query()
->where('name', 'LIKE', "%{$search}%")
->orWhere('slug', 'LIKE', "%{$search_any}%")
->where('status', 'Active')
->get();
我有用戶表,其中存盤列出產品的用戶,其關系如下
產品型號:
public function user()
{
return $this->belongsTo(User::class);
}
我在用戶表中有一個欄位type,我想如果用戶輸入搜索字串匹配型別,那么他們添加的所有產品也應該回傳我正在嘗試這段代碼,但我如何結合這兩個查詢
$products = Product::query()
->where('name', 'LIKE', "%{$search}%")
->orWhere('slug', 'LIKE', "%{$search_any}%")
->where('status', 'Active')
->get();
$productsAddedByUser = User::where('type', 'LIKE', "%{$search_any}%")->get();
// saved $productsAddedByUser result in this array $userIdarray
$productnew = Product::whereIn('user_id', $userIdarray)->get();
我想將和的結果結合$productnew起來$products
uj5u.com熱心網友回復:
首先將結果保存在 中$userIdarray,然后在產品查詢中:
$userIdarray = User::where('type', 'LIKE', "%{$search_any}%")->pluck('id');
$products = Product::query()
->where(
fn($query) => $query->where('name', 'LIKE', "%{$search}%")
->orWhere('slug', 'LIKE', "%{$search_any}%")
)
->where('status', 'Active')
->when(count($userIdarray), fn($query) => $query->whereIn('user_id', $userIdarray))
->get();
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/513055.html
