I want to know how to make relationship using laravel Model & Eloquent.
I have data structur something like this
UserTable
username
groups
id
GroupTable
id
name
remark
My question is how to display user groups (user can assign to many groups) and how to count how many users that assigned to each group.
thanks.
Update
public function store(Request $request){
$member = new Member();
$member->username = $request->input('name');
$member->gender = $request->input('gender');
$member->joindate = $request->input('joindate');
$member->remarks = $request->input('remarks');
if ($request->hasFile('photo')) {
if ($request->file('photo')->isValid()) {
$path = $this->upload($request);
}
}
$member->save();
foreach ($request->only('groups[]') as $key => $group){
$pivot = new pivot();
$pivot->user_id = ????? //how to get user id?
}
}
public function upload(Request $request)
{
$path = $request->file('photo')->store('profile');
return $path;
}
is that right? and how to get currently saved user_id (it has auto increment column).
You will need to create a pivot table assigning each user to their respective groups.
so basically your tables would be like:
User Table
id
username
Groups Table
id
name
remark
User -> Group Pivot Table
user_id
group_id
Then you can use an Eloquent relationship on your user model to define your relational method like so:
class User extends Model {
public function groups() {
return $this->belongsToMany(Group::class, 'user_group_pivot_table_name', 'user_id', 'group_id');
}
}
Finally, you can return a collection of all the user's groups by doing the following:
$user->groups();
The Laravel documentation on the Eloquent ORM is phenomenal too. Happy hunting.
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.