如何在不将对象加载到Laravel中的情况下获得关系计数 [英] How to get relationship counts without loading objects in laravel

查看:58
本文介绍了如何在不将对象加载到Laravel中的情况下获得关系计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a model customer and it has many projects. I want to find projects count without including its object.

客户模型包括:

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

Its giving me error:Call to a member function 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();

这篇关于如何在不将对象加载到Laravel中的情况下获得关系计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆