【问题标题】:Laravel - How do add DB::raw with specific Where clause to existing QueryLaravel - 如何将带有特定 Where 子句的 DB::raw 添加到现有查询
【发布时间】:2019-06-06 13:35:55
【问题描述】:

我想将带有特定 where 子句的 DB::raw() 添加到现有查询中。

我有这个查询:

    protected static $type = 
    [
        'daily' => 1,
        'weekly' => 2,
        'montly' => 3,
    ];

    $revenuedetails = DB::table("users")
        ->select("users.username", "users.email",DB::raw("DATE(users.created_at) as subscription_date"))
        ->where('users.plan', self::$type[$plan] ?? null);

但我想添加这个:

DB::raw("DATE(users.created_at) as expired_date"))
where('users.plan_status', 0)

应该就在旁边

DB::raw("DATE(users.created_at) as subscription_date"))

因此结构现在将是

用户名 |电子邮件 |订阅日期 |过期日期

我要添加

DB::raw("DATE(users.created_at) as expired_date"))

有自己特定的 where 子句

where('users.plan_status', 0)

到现有的查询。

请注意

where('users.plan', self::$type[$plan] ?? null)

是整体的 where 子句。

那么最终结果应该是

用户名 |电子邮件 |订阅日期 |过期日期

【问题讨论】:

    标签: laravel


    【解决方案1】:

    如果我对您的理解正确,如果计划状态 = 0,那么您想使用 created_at 日期作为到期日期吗?如果不是,那么 expired_date 应该为空?

    如果是这样,您可以使用 case 语句来完成此操作,例如 ...

    DB::raw(" CASE WHEN users.plan_status = 0 THEN DATE(users.created_at) ELSE null END AS expired_date ")
    

    【讨论】:

      【解决方案2】:

      您好,如果我理解得很好,您想在创建的别名上使用 where,这样您就可以使用“have()”而不是 where,如下所示:

      $revenuedetails = DB::table("users")
          ->select("users.username", "users.email",DB::raw("DATE(users.created_at) as subscription_date"), DB::raw("DATE(users.created_at) as expired_date"))
          ->having("subscription_date", "operador", "Value_condition")
          ->having("expired_date", "operador", "Value_condition")
          ->where('users.plan', self::$type[$plan] ?? null);
      

      您还可以查看以下参考:

      Can you use an alias in the WHERE clause in mysql?

      希望对你有帮助

      问候

      【讨论】:

      • 我说 DB::raw("DATE(users.created_at) as expired_date")) 仅在 where('users.plan_status', 0) 处有效。不适用于一般查询.因此,当 plan_status 为 0 时,它已经过期。所以不会影响其他字段。
      • 好的,我明白了,AndyChern 提供的解决方案适合你
      猜你喜欢
      • 2020-06-10
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 2019-11-12
      • 1970-01-01
      • 2015-04-28
      • 1970-01-01
      相关资源
      最近更新 更多