php - Laravel Eloquent thee tables relationship query

I have three mysql tables :
- students (constrained with
USER_ID
) - student_in_tournament (constrained with
STUDENT_ID
andTOURNAMENT_ID
) - tournaments
I need an eloquent query who take ALL students by specifiedUSER_ID
and if these students are in the student_in_tournament table, it needs to join with the tournament table.
If these students are not in the student_in_tournament, they don't need to join something.
At the end, I need ALL students from one specificUSER_ID
, with the tournament joined if he exists in the student_in_tournament table...
I tried a inner join, but it don't give me ALL the students, only these who are in the student_in_tournament table. I also triedStudent::with('studentInTournament.tournaments')
but it gives me 'null' in the tournaments
Thanks
Answer
Solution:
Try creating a M:N relation between yourStudent
andTournament
models. 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.
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');
}
// 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
@foreach($students as $student)
<!-- show student information -->
@forelse($student->tournaments as $tournament)
<!-- show tournament information -->
@empty
<!-- student has no tournaments -->
@endforelse
<hr>
@endforeach
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: xml parsing error: no root element found
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.