繁体   English   中英

Laravel 5.1具有许多直通关系

[英]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 UserTimesheet的列表。

我试图建立这样的关系:

/**
 * 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.

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