在Laravel Eloquent中将另一个表计为名称

时间:2018-09-01 09:25:02

标签: php sql laravel count eloquent

此sql查询有效

SELECT 
    users.*,
    (SELECT COUNT(*) FROM villaaz.elanlar
        WHERE elanlar.user_id = villaaz.users.id) AS elan_sayi
FROM villaaz.users 
INNER JOIN villaaz.elanlar on users.id = elanlar.user_id
WHERE elanlar.country_id=2 AND deleted_at IS NULL
GROUP BY users.id 
ORDER BY users.id ASC;

我想用Laravel编写它,请注意:这是我的Laravel代码的重要部分,问题在于此处其余部分的粗体字是问题。

$users = User::join('elanlar', 'elanlar.user_id', 'users.id')
    ->select([
       'users.*', 
        DB::select(DB::raw('COUNT(*) as elan_sayi FROM elanlar WHERE elanlar.user_id = users.id '))
    ])->where('elanlar.country_id', 19)->groupBy('users.id);
  

错误是:DB :: select(DB :: raw('COUNT(*)as elan_sayi FROM elanlar   在哪里elanlar.user_id = users.id'))

1 个答案:

答案 0 :(得分:1)

DB::select()执行查询。您必须将其删除并将SELECT添加到原始SQL:

$users = User::join('elanlar', 'elanlar.user_id', 'users.id')
    ->select([
       'users.*', 
        DB::raw('(SELECT COUNT(*) FROM elanlar WHERE elanlar.user_id = users.id) as elan_sayi')
    ])->where('elanlar.country_id', 19)->groupBy('users.id');