在Laravel 5中的select查询中使用属性值

时间:2018-04-20 09:31:50

标签: php mysql laravel laravel-5

模型Event - > id,guests_count,status。 型号Guest - > id,event_id,已确认。

我需要这样的东西:

Event::where('status', 'opened')->whereNotIn('id', $nId)
                        ->has('guests', '<' , XXX)
                        ->get();

相反XXX我需要使用guests_count值 - 每个事件的值不同 - 这可能吗?

我正在尝试获取所有未填充的事件(guests关系&lt; guests_count的数量。

我正在使用Laravel 5.4。

2 个答案:

答案 0 :(得分:1)

使用此:

Event::where('status', 'opened')->whereNotIn('id', $nId)
    ->withCount('guests as count')
    ->having('guests_count', '>', DB::raw('`count`'))
    ->get();

答案 1 :(得分:0)

你需要这个吗?

Event::select([DB::raw('count(guests) as count'),'id'])
    ->where('status','opened')
    ->whereNotIn('id', $nId)
    ->groupBy('guests')
    ->having('count','>',10)
    ->get();

sql输出

select count(guests) as count, `id` from `event` where `status` = 'opened' and `id` not in ([1,2,3]) group by `guests` having `count` > 10