Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ajsmith_codes's avatar

Query polymorphic AND one to many at same time?

I can retrieve polymorphic data by doing this:

$users = User::with('activity')->get();

Not all users are employees, but all employees are users.

Here is the query for that relationship:

   $employees = DB::table('employees')
        ->leftJoin('users', 'employees.id', '=', 'users.id')
        ->select('users.name','employees.*')
        ->get();

Now, how to combine the two? I need to get the activity for employees, but it's tied to the user_id, not employee_id. I hope that makes sense.

0 likes
1 reply
ajsmith_codes's avatar

Nevermind, I figured it out. Wish I could just delete this thread, but maybe this will help someone else:

    $employees = Employee::with('activity')
        ->leftJoin('users', 'employees.id', '=', 'users.id')
        ->select('users.name', 'employees.*')
        ->get();

Please or to participate in this conversation.