【问题标题】:Laravel withCount() subqueryLaravel withCount() 子查询
【发布时间】:2019-03-27 03:57:25
【问题描述】:

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

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

这是我正在寻找的东西的一个例子:

$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]);
    });

我该怎么做才能根据每个关系的子查询正确获取模型计数?

【问题讨论】:

  • 您能否包含您打算运行的原始 MySQL,或者添加一些示例数据?

标签: php laravel eloquent relationship


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-02-20
    • 2020-01-30
    • 2020-05-29
    • 2023-03-28
    • 2017-02-17
    • 2017-05-07
    • 2022-12-26
    • 1970-01-01
    相关资源
    最近更新 更多