与 N-M Laravel 相关的过滤器

问题描述 投票:0回答:1

我需要帮助,因为我不知道如何进行搜索,也不知道是否有办法通过查询来完成搜索,或者唯一的方法是使用 foreach。

我有两个表,一个名为“leads”的表,这是一个用户表和一个我命名为“plays”的游戏表。

用户可以有多个动作,一个动作属于单个用户。

在这个比赛表中,名为“时间”的一栏是他的比赛时间。

网站上有一个排行榜,列出了当天玩的用户以及玩时间最短的用户。我需要做的是把同月同日的所有玩家都带来,按时间从最短到最长的顺序排列。这已经完成了,现在的问题是。我不能带同一个用户两次,我必须过滤他的最佳动作并显示最佳动作,即花费最短时间的动作。

有人可以帮助我吗?下面我目前有疑问

查询:

$data = Lead::query();
$data = $data->with('plays', function($query){
        $query->whereMonth('played_at', '=', Carbon::now()->month)->whereDay('played_at', '=', Carbon::now()->day);
});
$data = $data->get();
laravel
1个回答
0
投票

with()
用于急切加载关系(并向急切加载的数据添加条件)。

如果您只想查询与该条件有关系的线索,则需要使用

whereHas

$leads = Lead::query()
    // Get only Leads that have plays where month/day is today's month/day
    ->whereHas('plays', function ($query) {
        $query->whereMonth('played_at', Carbon::now()->month)
            ->whereDay('played_at', '=', Carbon::now()->day);
    })
    // Eager load those Leads's plays relationship
    ->with('plays')
    ->get();
$leads = Lead::query()
    // Get only Leads that have plays where played_at's month/day is today's month/day
    ->whereHas('plays', function ($query) {
        $query->whereMonth('played_at', Carbon::now()->month)
            ->whereDay('played_at', '=', Carbon::now()->day);
    })
    // Eager load those Leads's plays relationship
    ->with(['plays' => function ($query) {
        // only eager load the plays where played_at's month/day is today's month/day
        $query->whereMonth('played_at', Carbon::now()->month)
            ->whereDay('played_at', '=', Carbon::now()->day);
    }])
    ->get();
© www.soinside.com 2019 - 2024. All rights reserved.