我对Laravel的hasManyThrough
关系(L5.2)有一些问题。
我有用户和组,而不是一个标准的连接表或一个定制的数据透视模型,我使用另一个有说服力的模型称为GroupMembership来链接这两者。以下是课程的相关部分:
class User extends Model {
use SoftDeletes;
protected $primaryKey = 'user_id';
public function groupMemberships() {
return $this->hasMany(GroupMembership::class);
}
}
class GroupMembership extends Model {
protected $primaryKey = 'group_membership_id';
public function user() {
return $this->belongsTo(User::class);
}
public function group() {
return $this->belongsTo(Group::class);
}
}
class Group extends Model {
use SoftDeletes;
protected $primaryKey = 'group_id';
public function groupMemberships() {
return $this->hasMany(GroupMembership::class);
}
public function users() {
return $this->hasManyThrough(User::class, GroupMembership::class,
'group_id', 'user_id', 'group_id'
);
}
}
我的问题是$组-
select `users`.*, `group_memberships`.`group_id` from `users`
inner join `group_memberships`
on `group_memberships`.`group_membership_id` = `users`.`user_id`
where `group_memberships`.`group_id` = '10'
and `users`.`deleted_at` is null
在该查询中,内部联接条件是错误的。而不是组成员身份。group\u membership\u id
,它实际上应该是group\u membership。用户id
。
我做错了什么?
多亏了这篇文章,我才明白这一点。我不想让有太多麻烦
。我只想belongToMany
指定自定义联接表:
public function users() {
return $this->belongsToMany(User::class, 'group_memberships');
}
您还可以添加withPivot
,以从连接模型中提取其他变量。
这里唯一的缺点是当使用$group-