如何在不将对象加载到Laravel中的情况下获得关系计数

时间:2019-03-28 05:06:29

标签: php laravel eloquent has-many

我有一个模型客户,并且有很多项目。我想找到不包含对象的项目计数。

客户模型包括:

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();

它给我错误:在整数上调用成员函数addEagerConstraints()

2 个答案:

答案 0 :(得分:3)

尝试一下

客户模型

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();

答案 1 :(得分:0)

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;
}

您可以为多个关系添加“计数”,也可以为查询添加约束:

$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;