Laravel withCount()子查询 [英] Laravel withCount() subquery

查看:44
本文介绍了Laravel withCount()子查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在withCount()上运行子查询?

How would I run a subquery on withCount()?

我有一个查询要运行多个计数,每个计数都有自己的子查询.

I have a query I want to run for multiple counts, each with their own subqueries.

以下是我正在寻找的东西的一个示例:

Here is an example of something that I'm looking for:

$date_from = Carbon::parse('1/1/2018');
$date_to = Carbon::parse('1/2/2018');

$models = Model::query()
    ->withCount('relation1', function (Builder $query) use ($date_from, $date_to) {
        $query->whereBetween('relation1.date1', [$date_from, $date_to])
              ->where('value1', true);
    })
    ->withCount('relation2', function (Builder $query) use ($date_from, $date_to) {
        $query->whereBetween('relation2.date2', [$date_from, $date_to])
              ->where('value2', false);
    })
    ->withCount('relation3', function (Builder $query) use ($date_from, $date_to) {
        $query->whereBetween('relation3.date3', [$date_from, $date_to]);
    });

我该怎么做,以便它将根据每个关系的子查询正确获取模型计数?

How do I do this so it will correctly grab the model counts based on the subquery per relation?

推荐答案

我认为您需要将子查询作为关联数组值传递:

I think you need to pass the sub-queries as associative array values:

https://laravel.com/docs/5.7/eloquent-Relationships#counting-related-models

例如

$date_from = Carbon::parse('1/1/2018');
$date_to = Carbon::parse('1/2/2018');

$models = Model::withCount([
        'relation1' => function (Builder $query) use ($date_from, $date_to) {
            $query->whereBetween('relation1.date1', [$date_from, $date_to])
                  ->where('value1', true);
        }, 
        'relation2' => function (Builder $query) use ($date_from, $date_to) {
            $query->whereBetween('relation2.date2', [$date_from, $date_to])
                  ->where('value2', false);
        },
        'relation3' => function (Builder $query) use ($date_from, $date_to) {
            $query->whereBetween('relation3.date3', [$date_from, $date_to]);
        }
    ])->get();

这篇关于Laravel withCount()子查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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