We have three tables. Get the Last Attendance Date from the attendance table of every user using eloquent relation users and user_attandance table
users
id - integer
name - string
attendance
id - integer
date - date
user_attandance
id - integer
attandance_id - integer
user_id - integer
Please help me.
Thanks in advance!
2
Answers
While ideally you’d find a pure query way to do this, I don’t think there will be a way that will be as performant as the following (which will consume a lot more memory):
Assuming you have a
belongsToMany
relationship betweenUser
andAttendance
set up already:Then your
$userList
variable will have one entry for each user containing the user data and their latest attendance data.While this is probably the fastest way to get this result, it will require all the attendance along with the associated users to be in memory though so if the user list is extensive or attendance record is large it will not work.
This solution is intended if you have a lot of memory to spare and want to minimise the number of queries you need to do.
In addition to the solution of @Muhammad Saqlain. You can use hasOneThrough to get the last date:
Then: