skip to Main Content

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


  1. 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 between User and Attendance set up already:

    $userlist = [];
    $list = Attendance::with('users')
        ->orderBy('date')
        ->get()
        ->map(function (Attendance $att) {
             $att->users->each(function (User $user) use ($att) {
                 $userList[$user->id] = [ $user, $att ];
             });
         });
    

    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.

    Login or Signup to reply.
  2. In addition to the solution of @Muhammad Saqlain. You can use hasOneThrough to get the last date:

    class User extends Model
    {
        public function lastAttendance()
        {
            return $this->hasOneThrough(Attendance::class, UserAttendance::class, 'user_id', 'id', 'id', 'attendance_id')
                        ->orderByDesc('date');
        }
    }
    

    Then:

    $users = User::with('lastAttendance')->get();
    foreach ($users as $user) {
        echo $user->name . ': ' . $user->lastAttendance->date . '<br>';
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search