[英]Eloquent relationship between user roles
I am creating an app where users have different roles.我正在创建一个应用程序,其中用户具有不同的角色。 Some of the roles include:
其中一些角色包括:
I have the following tables setup:我有以下表格设置:
user
role
role_user
The role_user
is a pivot table used to store the user_id
and role_id
. role_user
是一个数据透视表,用于存储user_id
和role_id
。
Now, when a Contractor is created, I trigger an event which assigns the user to the Contractor role in the database:现在,当创建承包商时,我会触发一个事件,该事件将用户分配给数据库中的承包商角色:
$user->roles()->save($role, ['cust_id' => $event->user->cust_id]);
The above line basically just creates a new row in the role_user
pivot table and points to the role_id
of a Contractor .上面的行基本上只是在
role_user
数据透视表中创建一个新行并指向Contractor的role_id
。 This results in the user having Contractor privileges.这导致用户具有承包商权限。
Also, within the event I need to assign the user to a Supervisor .此外,在事件中,我需要将用户分配给Supervisor 。 However, there is no Supervisor model.
但是,没有主管模型。 Supervisors are also stored in the user table and have a role of Supervisor assigned to them.
主管也存储在用户表中,并为其分配了主管角色。
How can I create a relationship between Contractors and Supervisors ?如何在承包商和主管之间建立关系?
Ideally, i'd like to use something like this to create the Contractor/Supervisor relationship in the pivot table:理想情况下,我想使用这样的东西在数据透视表中创建承包商/主管关系:
$user->supervisors()->save($supervisors, ['cust_id' => $event->user->cust_id]);
But i'm not sure how to setup my model...?但我不确定如何设置我的模型......?
/**
* The supervisors that belong to the user.
*
* @return Object
*/
public function supervisors()
{
return $this->belongsToMany('SimplyTimesheets\Models\User\User')->withTimestamps();
}
What your asking is possible, however your relationship model would look like this:您的要求是可能的,但是您的关系模型如下所示:
public function cands()
{
return $this->belongsToMany('Some\Model')->where('something', $something)->where('something', $something);
}
You would have to use where clauses to hard code a relationship between contractors and supervisors because there is no direct relationship between them both.您将不得不使用 where 子句来硬编码承包商和主管之间的关系,因为他们两者之间没有直接关系。
/ * Edit * / / * 编辑 * /
From your comment, you would have to approach that query with eager loading
your relationship like so:根据您的评论,您必须像这样
eager loading
您的关系来处理该查询:
User::has('supervisors')->join(...)->where(...)->get();
The query above would return all users which meet the roles criteria.上面的查询将返回满足角色条件的所有用户。 If you was just after one result you could create a
hasOne
relationship with your where clauses.如果您只是追求一个结果,则可以使用 where 子句创建
hasOne
关系。
public function relationship()
{
return $this->hasOne('Your\User_Role\Model', 'foreign_key', 'other_key')->where('role_id', supervisor)->where('role_id', contractor)
}
It all comes down to your application needs.这一切都取决于您的应用需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.