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

问题描述 投票:0回答:2

我有一个模范客户,它有很多项目。我想在不包含其对象的情况下查找项目数。

客户模型包括:

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

php laravel eloquent has-many
2个回答
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();

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;
© www.soinside.com 2019 - 2024. All rights reserved.