I have three mysql tables :
students (constrained with USER_ID)
student_in_tournament (constrained with STUDENT_ID and TOURNAMENT_ID)
tournaments
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.
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 specific USER_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 tried Student::with('studentInTournament.tournaments') but it gives me 'null' in the tournaments
Thanks
Try creating a M:N relation between your Student and Tournament 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');
}
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
#foreach($students as $student)
<!-- show student information -->
#forelse($student->tournaments as $tournament)
<!-- show tournament information -->
#empty
<!-- student has no tournaments -->
#endforelse
<hr>
#endforeach
Related
I have a employees table and a attendances table
In employees Model
public function Attendance(){
return $this->hasMany(Attendance::class, 'employees_id', 'id');
}
Attendances table i have these column
id, employees_id, in_time, out_time, attendance_status_id, remarks
I want return those employee who has al least one attendance for a specific month which i will input in month field and it will filter based on in_time column
You can use the has() function when getting the Employee details. The has will only return those records if the Employee has any relational data in the Attendance table. You can also refer this link.
$employees = Employee::has('Attendance')->get();
Now you can simply use the count() function the display the total Attendance of the Employee. For the count please refer this link.
#foreach ($employees as $employee)
Total attendance: {{ $employee->Attendance->count() }}
#endforeach
My application has the following entities:
Locations
Disciplines
Instructors
Disciplines and Instructors should be a many to many relationship, so in my Discipline model I have the following:
public function instructors() {
return $this->belongsToMany(
Instructor::class,
'location_discipline_instructors',
'discipline_id',
'instructor_id'
);
}
My pivot table contains the following fields:
location_id
discipline_id
instructor_id
I can use this relationship to fetch all disciplines with the associated instructors, but I need to filter these results by the location_id in the pivot table.
How should I approach this?
I tried using wherePivot() with location_id, but with that approach, I ended up with a list of all system disciplines with instructors for any discipline that had instructors associated. I continued to research and ended up with this solution:
Discipline::whereHas('instructors', function ($query) {
return $query->where('location_id', '=', $this->locationId);
})->with('instructors')->get();
i have an group table. My main table. So i have group_hotels table this table is a pivot table. (id, group_id, hotel_id)
Now in my blade group edit page, i want to list before added pivot table like this code:
My Group model:
public function hotels(){
return $this ->belongsToMany('App\Models\Hotel','group_hotels');
}
My controller:
$group = Group::find($id);
$hotels=Hotel::all();
My blade hotel select2 field:
#foreach($hotels as $hotel)
<option value="{{$hotel->id}}">{{$hotel->name}}</option>
#foreach ($group->hotels as $item)
<option value="{{$item->id}}">{{$item->name}}</option>
#endforeach
#endforeach
The output like this: http://prntscr.com/10v13ed
Now what i want to do, in my group_hotels pivot table, if hotel id exist in group_hotels except the in the pivot table id nothing come hotel table.
In short: If the hotel_id part in the group_hotels table is present in my hotel table, I do not want to call it in the hotel variable.
One option you have is to exclude the Hotel's you don't want in your list at the query level:
Hotel::whereNotKey($group->hotels->modelKeys())->get();
Let me explain the scenario.
i have tables:
competitions
id title body
then
books
id name user_id
then i have a pivot table to store participants
so
participants
id competition_id user_id
Now i have set some relationships for these models.
Competition model
public function participants()
{
return $this->belongsToMany('App\User');
}
User model
public function participatedCompetitions()
{
return $this->belongsToMany('App\Competition');
}
Now i am fetching one single competition and in that same query i need to fetch a list of books of the participants of that competition.
So how can i achieve this.
Thanks.
Here is how you get all the books:
$userIds = $competition->participant()->get()->pluck('id');
// $userIds is your collection of User Ids that is participant in that compititions.
$books = Book::whereIn('user_id',$userIds)->get();
I have 3 models and a pivot table:
SchoolYear - model
id
Course - model
id
schoolyear_id
course_student - pivot table
course_id
student_id
Student - model
id
Relationships are:
a SchoolYear hasMany Course
a Course belongsToMany Student trough course_student
a Student belongsToMany Course trough course_student
What is the fastest, more elegant way to find the students rolled in to a schoolyear and also to be able to sort it by Student properties?
$year = SchoolYear::firstOrCreate(['anul'=>Carbon::now()->year]);
$courses = $year->courses;
$students = collect([]);
foreach($courses as $course){
$course_students = $course->students;
foreach($course_students as $course_student){
$students->push($course_student);
}
}
dd($year, $students);
Eloquent provides a set of methods to query relationship existence. has() if there are not conditions, or whereHas() if there is a condition.
So, in your case, you want the students that have a related school year.
$year = SchoolYear::firstOrCreate(['anul'=>Carbon::now()->year]);
// assumes Student has a "courses" relationship,
// and Course has a "schoolYear" relationship
$students = Student::whereHas('courses.schoolYear', function ($query) use ($year) {
return $query->where('anul', $year->anul);
})
->get();
dd($year, $students);