[英]Laravel Subquery with Query Builder
I have a MySQL query like this:我有一个这样的 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
I tried converting it to an Eloquent query but this seems not to work:我尝试将其转换为 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();
You should create a relationship between your User
model and the model for the covis_transactions
table.您应该在您的User
模型和covis_transactions
表的模型之间创建关系。 (I'm gonna call it CovisTransaction
) (我将其称为CovisTransaction
)
# User.php
public function covis_transactions()
{
return $this->hasMany(CovisTransaction::class);
}
Then, you can use withCount
to get the aggregate count.然后,您可以使用withCount
来获取聚合计数。
User::query()
->select('id', 'nip', 'name')
->withCount('covis_transactions as total_survey')
->where('user_role_id', 7)
->groupBy('id')
->get();
You can convert subquery from a builder to a string :您可以将子查询从构建器转换为字符串:
DB::table('covis_transactions')->where('user_id', 'a.id')
DB::table('covis_transactions')->where('user_id', 'a.id')->toSql()
try it :试试看 :
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();
Or can use join
then count( covis_transactions
. id
)或者可以使用join
然后 count( covis_transactions
. id
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.