laravel 7: 如何在原始/查询生成器中使用 if / case 语句显示数据

laravel 7: how to display data with if / case statements in the raw / query builder

我想向 select 查询添加一个名为 status 的新字段,其中该字段的条件是使用 case / if 语句的 select 查询的结果。

这是我现在的table:

fullname is_active
Mr. X false
Mr. Z true

查询后我想要的期望:

fullname is_active status
Mr. X false Yes
Mr. Z true No

这是我的代码,但仍然显示错误: Undefined column: 7 ERROR: column "0" does not exist LINE 2: WHEN app.is_active = "0" THEN "Yes"

$data = DB::table('my_table as app')
   ->select('fullname','is_active',
             DB::raw('(CASE 
                WHEN app.is_active = "0" THEN "Yes" 
                ELSE "No" 
                END) AS status'))
   ->get();

非常感谢。

尝试对 MySQL 字符串文字使用单引号:

$data = DB::table('my_table as app')
    ->select('fullname', 'is_active',
             DB::raw("CASE app.is_active WHEN '0' THEN 'Yes' ELSE 'No' END AS status"))
    ->get();

如果以上解决了您的问题,那么我实际上会有点惊讶,因为 MySQL 通常会接受字符串文字的双引号。您看到的错误消息暗示 "0" 被解释为列名。