Reputation: 4885
I know that hasOneThrough
has been introduced to the latest Laravel build, however I can't really upgrade right now. What is the best way to do this?
I have got a users
table, which I can't change the structure off, but I need to assign a role
to these users, so I have created a pivot table, I want to add a method to my User
model to get the role, and the user can only have ONE.
Tables:
users
user_roles
user_assigned_roles
I could use hasManyThrough
, but this would expect many and I want to return a single model rather than a collection .
Upvotes: 0
Views: 544
Reputation: 14241
You could manage this with a combination of one-to-one & one-to-many relationships, and then access the role through an accessor:
`users` 1 --- 1 `user_assigned_roles` m ---- 1 `user_roles`
So, in a UserAssignedRole
model:
/** UserAssignedRole.php */
public function role()
{
return $this->belongsTo('App\UserRole');
}
Then in your User
model:
/** User.php */
public function assigned_role()
{
return $this->hasOne('App\UserAssignedRole');
}
// defining an accessor for your role:
public function getRoleAttribute()
{
return $this->assigned_role->role; // <--- Access the role of 'UserAssignedRole'
}
So in your controller (or wherever you want) you could do:
/** UsersController.php */
public function myFunction()
{
$user = User::find(1);
$role = $user->role; // <--
dd($role->name);
//
}
PS1: I strongly suggest you to upgrade to the latest version of Laravel to make use of the new features and also for security reasons, fixes etc.
PS2: There is package called Eloquent Has Many Deep by Jonas Staudenmeir that manages this kind of relationship (and more) for you.
Upvotes: 2