php 如何求具有多个关系函数和

vfh0ocws  于 2023-03-11  发布在  PHP
关注(0)|答案(1)|浏览(79)

我怎样才能得到有很多关系深总和?
我有3个模型(客户端/横幅/横幅日志)
每一种关系都是这样的:

Client -> Banner : hasMany 

Banner -> BannerLog : hasMany 
BannerLog has view_count, click_count. that would increase every time user access or click.

我可以让所有客户端与他们的横幅和横幅日志如下:

$clients = Client::query()
        ->with('banners')
        ->with(['banners.banner_logs' => function ($q) {
            $q->whereBetween('reg_date', [$this->start, $this->end]);
        }])
        ->get();

但我希望获得banner_logs表中view_count、click_count的总和。
我该怎么做呢?
给予我解决这个问题的正确密码

omqzjyyz

omqzjyyz1#

您可以执行以下操作:

$clients = Client::query()
                ->with(['banners'=> function( $q ) use ($start, $end)  {
                    $q->withSum (['banner_logs as view_count_sum' => fn ($query) => $query->whereBetween('reg_date', [$start, $end])], 'view_count')
                        ->withSum (['banner_logs as click_count_sum' => fn ($query) => $query->whereBetween('reg_date', [$start, $end])], 'click_count');
                }])
                ->orderBy('id', 'desc')
                ->paginate();

相关问题