Hi,
I just begin to learn Laravel in few days.
In my situation, I have three tables:
users(
id,
name)
groups(
id,
name)
group_has_users(
group_id,
user_id)
group has many users, but user just belong one group, how about the below Relationship,
then after I save a group, how to take the ID of group and save to "group_has_users" table
in Group model I have:
public function users()
{
return $this->morphMany('App\User', 'group_has_users');
}
in User model I have:
public function group()
{
return $this->hasOne('App\Group');
}
public function users()
{
return $this->belongsToMany('App\User', 'group_has_users');
}
in User model I have:
public function group()
{
return $this->hasOne('App\Group');
}
Create
$user = User::find(auth()->id());
$res = $user->group()->attach($groupId) // single row will be created
$groupIds = [1,2,3];
$res = $user->group()->attach($groupIds) // multiple row will be created
at above coding user id will be automatically insert due to relationship
If you have the access to modify the database a better design would be to have a group_id column on your users table and delete the group_has_users pivot table.
It's just a one to many relationship:
User model:
public function group()
{
return $this->belongsTo('App\Group');
}
Group model:
public function user()
{
return $this->hasMany('App\User');
}