php - Laravel withCount() 子查询

标签 php laravel eloquent relationship

如何在 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]);
    });

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

最佳答案

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

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

关于php - Laravel withCount() 子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52940125/

相关文章:

php - PHP 和 Laravel 的特性

php - Laravel Eloquent 计数乘法

php - Laravel 工厂并选择了一个唯一的 ownTo 实例

php - Laravel 关系(与)

php - 将 mysql datetime 更改为 php datetime-local 不通过 strtotime() 工作

laravel - 仅显示可见的项目和组中有项目的组

PHP:用逗号(,)拆分字符串但忽略方括号内的任何内容?

php - laravel中抽象Model类如何处理 "::find()"、 "::where()"等静态动态方法调用

php jquery动态保存复选框

php - MySQL 返回所有结果而不重复数据