Laravel withCount() subquery

瘦欲@ 提交于 2021-01-01 07:01:30

问题


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?


回答1:


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

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

E.g.

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


来源:https://stackoverflow.com/questions/52940125/laravel-withcount-subquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!