Laravel 使用查询生成器的子查询

Laravel Subquery with Query Builder

我有一个这样的 MySQL 查询:

SELECT
    a.id,
    a.nip,
    a.name,
    COUNT(
      (
        SELECT id
        FROM covis_transactions
        WHERE user_id = a.id
      )
    ) AS total_survey
FROM users a
WHERE a.user_role_id = 7
GROUP BY a.id

我尝试将其转换为 Eloquent 查询,但这似乎不起作用:

DB::table('users as a')
    ->selectRaw("a.id, a.nip, a.name, COUNT(".DB::table('covis_transactions')->where('user_id', 'a.id').") as total_survey")
    ->where('a.user_role_id', 7)
    ->groupBy('a.id')
    ->get();

您可以将子查询从构建器转换为字符串:

DB::table('covis_transactions')->where('user_id', 'a.id')

DB::table('covis_transactions')->where('user_id', 'a.id')->toSql()

试一试:

DB::table('users as a')
            ->selectRaw("a.id, a.nip, a.name, COUNT(" . DB::table('covis_transactions')->where('user_id', 'a.id')->toSql() . ") as total_survey")
            ->where('a.user_role_id', 7)
            ->groupBy('a.id')
            ->get();

或者可以使用join然后计数(covis_transactions.id)

您应该在 User 模型和 covis_transactions table 的模型之间建立关系。 (我要称它为CovisTransaction

# User.php
public function covis_transactions()
{
    return $this->hasMany(CovisTransaction::class);
}

然后,您可以使用 withCount 来获取总计数。

User::query()
    ->select('id', 'nip', 'name')
    ->withCount('covis_transactions as total_survey')
    ->where('user_role_id', 7)
    ->groupBy('id')
    ->get();