php - 在 Laravel 中使用 Eloquent 检索关系的不同关系

标签 php laravel eloquent

假设我有一个模型:种族参与者团队
这些关系:种族 1-N 参与者 N-1 团队

换个角度看:

races  1 - N  participants
teams  1 - N  participants

用 Laravel 术语来说:

/* Inside Race model */
public function participants()
{
    return $this->hasMany(Participant::class);
}


/* Inside Team model */
public function participants()
{
    return $this->hasMany(Participant::class);
}


/* Inside Participant model */
public function race()
{
    return $this->belongsTo(Race::class);
}
public function team()
{
    return $this->belongsTo(Team::class);
}

participants表,看起来像这样:

id | team_id | race_id | [a lot of other columns...]
------------------------------
 1 |    1    |    1    |
 2 |    1    |    1    |
 3 |    2    |    1    |
 4 |    2    |    1    |

在上面的例子中,我知道种族 ID 12 teams .

我可以count他们这样做:

$race = Race::find(1);
$number = $race->participants()->distinct()->count('team_id');

问题

Counting团队数量很酷,但我想访问相应的 Team 的列表模型实例,以便我可以将它们用于进一步的操作(例如在 foreach 循环内)。
我尝试了很多事情但没有成功。
像这样的事情:

$teams = $race->participants()->distinct()->[...] // Don't know what to put here

等效的 SQL 查询是:

SELECT teams.* FROM teams
INNER JOIN participants ON participants.team_id = teams.id
INNER JOIN races ON races.id = participants.race_id
WHERE races.id = 1
GROUP BY teams.id

结果是:

teams query

participants表包含以下内容:

participant query

我想知道我是否可以使用Eloquent来做到这一点而不是使用Query/Builder DB::直接方法?

编辑1

我最接近的结果:

$race->participants()->distinct()->get('team_id')

result 1

然后使用 team_id 的列表我可以使用 Team::find([list of IDs]) 访问团队但它对我来说看起来很贪婪。

编辑2

我忘记了一些信息:

  • participants.team_id列是 NULLABLE因为:
    • racesteamsparticipants
    • racesparticipants (没有 team )

最佳答案

我认为您无法通过 $race 实例轻松访问它。
但是,您可以在 Team 模型上使用 whereHas 方法:

$race = Race::find(1);
$teams = Team::whereHas('participants', function ($query) use ($race) {
    $query->where('race_id', $race->id);
})->get();  // ->count() also works

See documentation

关于php - 在 Laravel 中使用 Eloquent 检索关系的不同关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61891205/

相关文章:

php - 向表列添加标题,并从 SQL 输出总计

php - 使列与 id 相同

php - 单击 Bootstrap 下拉元素并更改值

php - 无法在 Laravel 中模拟部分 Log 外观

php - 在 Laravel 中查询关系

PHP 文件删除权限被拒绝

php - Laravel 验证总是从 API 返回 200 OK

javascript - Laravel MIX,如何在多个文件中使用单个函数

php - 在 Laravel 中添加外键约束时出错 - 按正确顺序迁移

laravel - 加载 hasMany 关系的最后一条记录