php - Laravel: Complicated Eloquent Relationship - hasManyThrough or belongsToMany approach? -


i have 3 models (organization, user, visit) , 4 tables (organizations, users, organization_user, visits). i'm trying accumulative total of user visits organization.

organization ------------ id, name  user --------- id, name  organization_user ---------------- id, organization_id, user_id  visit -------------- id, user_id views 

just clarify, there no organization_user model, pivot table used user , organization:

$organization->belongstomany('user'); $user->belongstomany('organization'); 

i query user_ids pivot table group_id, , visits each user_id, what's more eloquent approach?

a user hasmany visits , visit belongsto user. visit doesn't belong organization.

solved using wherein(). no change current relationship setup...to accumulative views did this:

$org = organization::find($org_id); return db::table('visits')->wherein('user_id', $org->users->modelkeys())->sum("views"); 

the modelkeys() returns user ids tied organization. sum of views users.

*note it's important use organization::find , not db::table('organization') in order maintain eloquent relationship. otherwise $organization->users give error.


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -