简体   繁体   English

Laravel withCount()返回null

[英]Laravel withCount() returns null

I need to count the results of Many-to-Many relation subquery. 我需要计算多对多关系子查询的结果。

return $q->withCount(['users' => function($q) {
    $q->select("Users.Id as Id_user","Users.Name");
}])->get()

This code doesn't work. 此代码无效。 It return null. 它返回null。

However, that works fine and successfully adds users_count column: 但是,这可以正常工作并成功添加users_count列:

return $q->withCount(['users'])->get();

But I need to make select subquery to select specific columns from the relation so I need my first variant get to work. 但是我需要进行选择子查询以从关系中选择特定的列,因此我需要第一个变体开始工作。

Thanks a lot! 非常感谢!

when you use Count or withCount method, the query builder does a select count(id) as aggregate 当您使用CountwithCount方法时,查询构建器将select count(id) as aggregate

if in the condition par of the withCount you override the select part. 如果在withCount的条件参数中,您覆盖select部分。 it breaks 坏了

return $q->withCount(['users' => function($q) {
    //here you are supposed to do condition, not a select
    $q->select("Users.Id as Id_user","Users.Name");
}])->get()

if you want the id and the name of the user, use with 如果您想要用户名和用户名,请with

return $q->withCount(['users'])
    ->with(['users' => function($q) {
        $q->select("Users.Id as Id_user","Users.Name");
    }])
    ->get()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM