我有簡單的代碼部分來檢測折扣類型,我添加了另一種類型,但在這種情況下如何正確使用運算符OR( ) ?或做某事。這行不通||->where('taken', "N")"R"->where('taken', "N" || "R")$code = Discount::where('code',$discount_code)
->where('expiry','>',Carbon::now()->toDateString())
->where('subscription', $subscription)
->where('taken', "N")
->first();
4 回答

揚帆大魚
TA貢獻1799條經驗 獲得超9個贊
在這種情況下,使用whereIn()
數組并將其傳遞給第二個參數
-where('taken', "N" || "R")
到
whereIn('taken', ["N","R"])
所以你的最終代碼將是
$code = Discount::where('code',$discount_code) ->where('expiry','>',Carbon::now()->toDateString()) ->where('subscription', $subscription) ->whereIn('taken', ["N","R"]) ->first();
參考鏈接https://laravel.com/docs/7.x/queries#where-clauses

大話西游666
TA貢獻1817條經驗 獲得超14個贊
您可以使用 的另一個功能->where
,即它接受回調,這將生成一個“嵌套”函數:
Discount::where('code',$discount_code) ->where('expiry','>',Carbon::now()->toDateString()) ->where('subscription', $subscription) ->where(function($q) use($abc) { $q->where('taken', "N") ->orWhere('taken', "R"); })->get();
如果您對 SQL 感到滿意,$q->where('taken', "N")->orWhere('taken', "R");
將被包裝在 上( ... )
,這樣您就可以使用 SQL
WHERE expiry > *a date* AND subscription = *a value* and (taken = 'N' OR taken = 'R')

慕慕森
TA貢獻1856條經驗 獲得超17個贊
為了避免使用 的不穩定布爾邏輯expiry > x and taken = N or taken = R
,如果采取的是 R 并忽略到期,則 will 結果為 true。您可以回電以在您的條件周圍添加括號。
->where(function ($query) { $query->where('taken', 'N') ->orWhere('taken', 'R'); });
這將產生與此類似的查詢。這應該給出預期的結果。
expiry > x and (taken = N or taken = R)

慕工程0101907
TA貢獻1887條經驗 獲得超5個贊
或者可以使用Where方法
$code = Discount::where('code',$discount_code) ->where('expiry','>',Carbon::now()->toDateString()) ->where('subscription', $subscription) ->where('taken', "N") ->orWhere('taken', "R") ->first();
- 4 回答
- 0 關注
- 199 瀏覽
添加回答
舉報
0/150
提交
取消