[英]Laravel 5.1 has many through relationship
I have the following tables setup: 我有以下表格设置:
User
- id
Timesheet
- id
- user_id
Users also have roles. 用户也具有角色。 A user can have an employee
role or a supervisor
role. 用户可以具有employee
角色或supervisor
角色。 Users can be assigned to supervisors, so I have setup the following relationship on the User
model: 可以将用户分配给主管,因此我在User
模型上设置了以下关系:
/**
* The supervisors that are assigned to the user.
*
* @return Object
*/
public function supervisors()
{
return $this->belongsToMany('App\Models\User\User', 'supervisor_user', 'user_id', 'supervisor_id')->withTimestamps();
}
The supervisor_user
table is a pivot table and has data like so: supervisor_user
表是数据透视表,其数据如下:
user_id supervisor_id
1 5
The above means that the user with id of 1
is assigned to the supervisor with id of 5
. 以上意味着将ID为1
的用户分配给ID为5
的主管。
I now want to be able to get a list of Timesheet
s that belong to User
who are assigned to a Supervisor
. 现在,我希望能够获取属于分配给Supervisor
User
的Timesheet
的列表。
I have tried setting up a relationship like so: 我试图建立这样的关系:
/**
* Timesheets that belong to assigned users.
*
* @return Object
*/
public function supervisorTimesheets()
{
return $this->hasManyThrough('App\Models\Timesheet\Timesheet', 'Costain\Models\User\User', 'id', 'user_id');
}
However, this results in the following SQL query which does not join my supervisor_user
table in order to only return timesheets that belong to users who are assigned to this supervisor: 但是,这将导致以下SQL查询,该查询不加入我的supervisor_user
表,以便仅返回属于已分配给该supervisor的用户的时间表。
select `timesheet`.*, `user`.`id` from `timesheet` inner join `user` on `user`.`id` = `timesheet`.`user_id` where `user`.`id` = 1
Does anyone know how I can return timesheets that belong to users who are assigned to a specific supervisor? 有谁知道我如何返回属于分配给特定主管的用户的时间表?
HasManyThrough
can only be used with HasOne
/ HasMany
relationships. HasManyThrough
只能与HasOne
/ HasMany
关系一起使用。 It cannot be used with a many to many ( BelongsToMany
) relationship. 它不能与多对多( BelongsToMany
)关系一起使用。
I think what you're really looking for is a whereHas()
query: 我认为您真正要寻找的是whereHas()
查询:
$supervisor = User::find(5);
$timesheets = Timesheet::whereHas('user.supervisors', function ($query) use ($supervisor) {
$query->where('id', $supervisor->id);
})->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.