Search code examples
phplaraveleloquentrelationships

Laravel: Complicated Eloquent Relationship - hasManyThrough or belongsToMany approach?


I have three Models (Organization, User, Visit) and 4 tables (organizations, users, organization_user, visits). I'm trying to get the accumulative total of user visits for an Organization.

Organization
------------
id,
name

User
---------
id,
name

Organization_User
----------------
id,
organization_id,
user_id

Visit
--------------
id,
user_id
views

Just to clarify, there is no Organization_User model, that is just the pivot table used by User and Organization:

$organization->belongsToMany('User');
$user->belongsToMany('Organization');

I could query all the user_ids from the pivot table by group_id, and then get all the visits for each user_id, but what's the more Eloquent approach?

A User hasMany Visits and a Visit belongsTo a User. A Visit doesn't belong to an Organization.


Solution

  • Solved it by using whereIn(). Basically with no change to my current relationship setup...to get accumulative views I did this:

    $org = Organization::find($org_id);
    return DB::table('visits')->whereIn('user_id', $org->users->modelKeys())->sum("views");
    

    The modelKeys() returns all the user ids tied to that Organization. Then I get the sum of all the views for those users.

    *Note it's also important to use Organization::find and not DB::table('organization') in order to maintain the Eloquent relationship. Otherwise $organization->users will give an error.