简体   繁体   中英

How to retrieve data from additional columns in a pivot table and also be able to update it in laravel 5.2

I was working on making a group functionality for my website which uses a many to many relationship between groups and users.

My User model looks like this:

public function groups(){
    return $this->belongsToMany('App\Group')->withPivot('role')->withTimestamps();
}

My Groups model looks like this:

 public function users(){
     return $this->belongsToMany('App\User')->withPivot('role')->withTimestamps();
}

So my third column has the name of role which is a string variable and is set to a default of "member" for members of my group and I set it to "admin" for the actual user who creates a new group. But I want the admin to have the option of making multiple members admins as well which would require me to check weather the current current user who sent the request is an admin or not. If he is, then I wanna be able to take his request of making a member an admin which would require me to update the role for that particular "member" to an "admin".

In the laravel documentation it only shows you how to attach and detach data in a pivot table and else where I have only seen methods of retrieving data from the first two columns but how can I do the same for additional columns and also be able to update it using the updateExistingPivot method?

You could access the column simply using pivot eg :

$user->pivot->role

Take a look at Retrieving Intermediate Table Columns in documentation Eloquent Relationships .

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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