[英]Laravel Eloquent thee tables relationship query
I have three mysql tables :我有三个 mysql 表:
USER_ID
)USER_ID
约束)STUDENT_ID
and TOURNAMENT_ID
) STUDENT_ID
和TOURNAMENT_ID
约束)I need an eloquent query who take ALL students by specified USER_ID
and if these students are in the student_in_tournament table, it needs to join with the tournament table.我需要一个雄辩的查询,通过指定的
USER_ID
获取所有学生,如果这些学生在student_in_tournament表中,则需要加入锦标赛表。
If these students are not in the student_in_tournament , they don't need to join something.如果这些学生不在student_in_tournament 中,则他们不需要加入某些东西。
At the end, I need ALL students from one specific USER_ID
, with the tournament joined if he exists in the student_in_tournament table...最后,我需要来自一个特定
USER_ID
所有学生,如果他存在于 student_in_tournament 表中,则参加锦标赛......
I tried a inner join, but it don't give me ALL the students, only these who are in the student_in_tournament table.我尝试了内部联接,但它并没有给我所有的学生,只有那些在student_in_tournament表中的学生。 I also tried
Student::with('studentInTournament.tournaments')
but it gives me 'null' in the tournaments我也试过
Student::with('studentInTournament.tournaments')
但它在锦标赛中给了我 'null'
Thanks谢谢
Try creating a M:N relation between your Student
and Tournament
models.尝试在您的
Student
和Tournament
模型之间创建 M:N 关系。 Since your table and column names do not conform to what Eloquent expects, you'll need to pass all 4 parameters when creating the relationship.由于您的表名和列名不符合 Eloquent 的要求,因此您需要在创建关系时传递所有 4 个参数。
https://laravel.com/docs/8.x/eloquent-relationships#many-to-many-model-structure https://laravel.com/docs/8.x/eloquent-relationships#many-to-many-model-structure
// Student model
public function tournaments()
{
return $this->belongsToMany(Tournament::class, 'student_in_tournament', 'STUDENT_ID', 'TOURNAMENT_ID');
}
https://laravel.com/docs/8.x/eloquent-relationships#many-to-many-defining-the-inverse-of-the-relationship https://laravel.com/docs/8.x/eloquent-relationships#many-to-many-defining-the-inverse-of-the-relationship
// Tournament model
public function students()
{
return $this->belongsToMany(Student::class, 'student_in_tournament', 'TOURNAMENT_ID', 'STUDENT_ID');
}
$students = Student::query()
->where('USER_ID', $user_id) // or whereIn('USER_ID', $user_ids) if you have multiple user ids
->with('tournaments')
->get();
https://laravel.com/docs/8.x/blade#loops https://laravel.com/docs/8.x/blade#loops
@foreach($students as $student)
<!-- show student information -->
@forelse($student->tournaments as $tournament)
<!-- show tournament information -->
@empty
<!-- student has no tournaments -->
@endforelse
<hr>
@endforeach
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.