为了账号安全,请及时绑定邮箱和手机立即绑定

PHP如何正确使用OR

PHP如何正确使用OR

PHP
慕妹3146593 2024-01-19 15:04:05
我有简单的代码部分来检测折扣类型,我添加了另一种类型,但在这种情况下如何正确使用运算符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


查看完整回答
反对 回复 2024-01-19
?
大话西游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')



查看完整回答
反对 回复 2024-01-19
?
慕慕森

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)


查看完整回答
反对 回复 2024-01-19
?
慕工程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();


查看完整回答
反对 回复 2024-01-19
  • 4 回答
  • 0 关注
  • 41 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信