[英]Laravel 5.1 has many through relationship
我有以下表格設置:
User
- id
Timesheet
- id
- user_id
用戶也具有角色。 用戶可以具有employee
角色或supervisor
角色。 可以將用戶分配給主管,因此我在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();
}
supervisor_user
表是數據透視表,其數據如下:
user_id supervisor_id
1 5
以上意味着將ID為1
的用戶分配給ID為5
的主管。
現在,我希望能夠獲取屬於分配給Supervisor
User
的Timesheet
的列表。
我試圖建立這樣的關系:
/**
* 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');
}
但是,這將導致以下SQL查詢,該查詢不加入我的supervisor_user
表,以便僅返回屬於已分配給該supervisor的用戶的時間表。
select `timesheet`.*, `user`.`id` from `timesheet` inner join `user` on `user`.`id` = `timesheet`.`user_id` where `user`.`id` = 1
有誰知道我如何返回屬於分配給特定主管的用戶的時間表?
HasManyThrough
只能與HasOne
/ HasMany
關系一起使用。 它不能與多對多( BelongsToMany
)關系一起使用。
我認為您真正要尋找的是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.