我有一个包含以下字段的表:name
和plan_status
。
plan_status
可以是0
或1
。 1
处于活动状态,0
处于非活动状态。我要显示|name|active|inactive|
。
我只能运行显示活动和不活动查询的查询。
型号:
protected $fillable = [
'name', 'plan_status'
];
控制器:
$actives = DB::table('users')
->select(DB::raw('count(*) as active'))
->where('plan_status', 1)
我希望查询同时显示活动和不活动的名称:|name|active|inactive|
。
答案 0 :(得分:2)
这里是查询,它将为您提供所需的确切结果
$actives = DB::table('users')
->selectRaw('
name,
IF((plan_status = 1), "Yes", "No") as active,
IF((plan_status = 0), "Yes", "No") as inactive,
IF((plan_status = 2), "Yes", "No") as undefined
')
->get()
尝试一下并检查。我认为这可以解决您的问题。
已编辑
获取明智的状态
$actives = DB::table('users')
->selectRaw('
name,
IF((plan_status = 1), COUNT(*), "0") as active,
IF((plan_status = 0), COUNT(*), "0") as inactive,
IF((plan_status = 2), COUNT(*), "0") as undefined
')
->groupBy('plan_status')
->get()
喜欢
尝试两种解决方案。
答案 1 :(得分:0)
使用分组依据尝试此操作
DB::table('users')
->select('name',
DB::raw('IF((plan_status = 1), count(*), 0) as active'),
DB::raw('IF((plan_status = 0), count(*), 0) as inactive'),
)->groupBy('plan_status')->get()