简体   繁体   English

Laravel:复杂的口才关系-hasManyThrough还是belongsToMany方法?

[英]Laravel: Complicated Eloquent Relationship - hasManyThrough or belongsToMany approach?

I have three Models (Organization, User, Visit) and 4 tables (organizations, users, organization_user, visits). 我有三个模型(组织,用户,访问)和4个表(组织,用户,organization_user,访问)。 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_User模型,这只是User和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? 我可以通过group_id从数据透视表中查询所有user_id,然后获取每个user_id的所有访问次数,但是还有什么更雄辩的方法呢?

A User hasMany Visits and a Visit belongsTo a User. 用户有多次访问,而访问属于用户。 A Visit doesn't belong to an Organization. 访问不属于组织。

Solved it by using whereIn(). 通过使用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. modelKeys()返回与该组织相关的所有用户ID。 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. *请注意,使用Organization :: find而非DB :: table('organization')来保持口才关系也很重要。 Otherwise $organization->users will give an error. 否则$ organization-> users将给出错误。

I think you might want a 'Has Many Through' relationship like so: 我认为您可能想要像这样的“拥有很多通过”的关系:

class Organization extends Model
{
    public function visits()
    {
        return $this->hasManyThrough('App\Visit', 'App\User');
    }
}

Then you could call count() . 然后,您可以调用count()

Laravel 5.1 doc Laravel 5.1文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM