如何在不加载 laravel 中的对象的情况下获取关系计数

How to get relationship counts without loading objects in laravel

我有一个模范客户,它有很多项目。我想找到不包括其对象的项目计数。

客户模型包括:

public function numberOfProjects()
{
    return $this->hasMany(Project::class)->count();
}

在我的控制器中查询:

 $customers = Customer::where(['is_active'=>1])
                                ->with(['customerContactInformation'=> function ($query) {
                                    $query->where('is_active',1);
                                }, 'numberOfProjects'])
                                ->skip($skip)->take(10)
                                 ->get();

它给我 error:Call 一个成员函数 addEagerConstraints() on integer

试试这个

客户模型

public function numberOfProjects()
{
    return $this->hasMany(Project::class);
}

控制器

$customers = Customer::where(['is_active'=>1])
                    ->with(['customerContactInformation'=> function ($query) {
                        $query->where('is_active',1);
                    }])
                    ->withCount('numberOfProjects') //you can get count using this
                    ->skip($skip)
                    ->take(10)
                    ->get();

应该可以了

$customers = Customer::withCount('numberOfProjects')->get();

WithCount 特定状态

$customers = Customer::withCount([
                        'numberOfProjects',
                        'numberOfProjects as approved_count' => function ($query) {
                            $query->where('approved', true);
                        }
                    ])
                    ->get();
class Tutorial extends Model
{
    function chapters()
    {
        return $this->hasMany('App\Chapter');
    }

    function videos()
    {
        return $this->hasManyThrough('App\Video', 'App\Chapter');
    }
}

然后你可以做:

Tutorial::withCount(['chapters', 'videos'])

统计相关模型 如果你想计算一个关系的结果数量而不实际加载它们,你可以使用 withCount 方法,它会在你的结果模型上放置一个 {relation}_count 列。例如:

$posts = App\Post::withCount('comments')->get();

foreach ($posts as $post) {
    echo $post->comments_count;
}

您可以为多个关系添加 "counts" 以及向查询添加约束:

$posts = App\Post::withCount(['votes', 'comments' => function ($query) {
    $query->where('content', 'like', 'foo%');
}])->get();

echo $posts[0]->votes_count;
echo $posts[0]->comments_count;

您还可以为关系计数结果设置别名,允许对同一关系进行多次计数:

$posts = App\Post::withCount([
    'comments',
    'comments as pending_comments_count' => function ($query) {
        $query->where('approved', false);
    }
])->get();

echo $posts[0]->comments_count;

echo $posts[0]->pending_comments_count;

如果您将 withCount 与 select 语句结合使用,请确保在 select 方法之后调用 withCount:

$posts = App\Post::select(['title', 'body'])->withCount('comments');

echo $posts[0]->title;
echo $posts[0]->body;
echo $posts[0]->comments_count;