Laravel:复杂的 Eloquent 关系 - hasManyThrough 或 belongsToMany 方法?
Laravel: Complicated Eloquent Relationship - hasManyThrough or belongsToMany approach?
我有三个模型(组织、用户、访问)和 4 个 tables(组织、用户、organization_user、访问)。我正在尝试获取组织的累计用户访问总数。
Organization
------------
id,
name
User
---------
id,
name
Organization_User
----------------
id,
organization_id,
user_id
Visit
--------------
id,
user_id
views
澄清一下,没有 Organization_User 模型,这只是用户和组织使用的支点 table:
$organization->belongsToMany('User');
$user->belongsToMany('Organization');
我可以通过 group_id 从枢轴 table 查询所有 user_ids,然后获取每个 user_id 的所有访问,但更重要的是 Eloquent 方法?
一个用户有很多次访问,一次访问属于一个用户。访问不属于组织。
我想你可能想要这样的 'Has Many Through' 关系:
class Organization extends Model
{
public function visits()
{
return $this->hasManyThrough('App\Visit', 'App\User');
}
}
那你可以打电话给count()
.
使用 whereIn() 解决了这个问题。基本上没有改变我当前的关系设置...为了获得累积的观看次数,我这样做了:
$org = Organization::find($org_id);
return DB::table('visits')->whereIn('user_id', $org->users->modelKeys())->sum("views");
modelKeys() returns 绑定到该组织的所有用户 ID。然后我得到这些用户的所有视图的总和。
*请注意,为了保持 Eloquent 关系,使用 Organization::find 而不是 DB::table('organization') 也很重要。否则 $organization->users 会报错。
我有三个模型(组织、用户、访问)和 4 个 tables(组织、用户、organization_user、访问)。我正在尝试获取组织的累计用户访问总数。
Organization
------------
id,
name
User
---------
id,
name
Organization_User
----------------
id,
organization_id,
user_id
Visit
--------------
id,
user_id
views
澄清一下,没有 Organization_User 模型,这只是用户和组织使用的支点 table:
$organization->belongsToMany('User');
$user->belongsToMany('Organization');
我可以通过 group_id 从枢轴 table 查询所有 user_ids,然后获取每个 user_id 的所有访问,但更重要的是 Eloquent 方法?
一个用户有很多次访问,一次访问属于一个用户。访问不属于组织。
我想你可能想要这样的 'Has Many Through' 关系:
class Organization extends Model
{
public function visits()
{
return $this->hasManyThrough('App\Visit', 'App\User');
}
}
那你可以打电话给count()
.
使用 whereIn() 解决了这个问题。基本上没有改变我当前的关系设置...为了获得累积的观看次数,我这样做了:
$org = Organization::find($org_id);
return DB::table('visits')->whereIn('user_id', $org->users->modelKeys())->sum("views");
modelKeys() returns 绑定到该组织的所有用户 ID。然后我得到这些用户的所有视图的总和。
*请注意,为了保持 Eloquent 关系,使用 Organization::find 而不是 DB::table('organization') 也很重要。否则 $organization->users 会报错。