I have 'users' table where it has column groupID(foreign key) for table 'groups'. All user can have many groups but as for now I can only insert one group for each user. What I want to achieve is whenever user want to create new groups next time, the groupID column will have data like this [1,2]. Sorry for my bad english.
This is my code
public function addgroup(Request $req)
{
$data = new Group;
$data->groupName = $req->groupName;
$data->groupDesc = $req->groupDesc;
$data->userId = Auth::user()->id;
$data->save();
$g=User::find(Auth::user()->id);
$g->groupID =implode(',', (array)$data->id);
$g->save();
return redirect('redirect');
}
CodePudding user response:
You are wrong in designing database, if users can have many group and each group can have many user, then you should create many-to-many relationship, not by storing group id in users table in array format.
this is what you should do instead.
- create user table
- create group table
- create user_group table as pivot table storing user_id and group_id
then you will store the group relation in that pivot table (user_group)
read this documentation for your reference https://laravel.com/docs/9.x/eloquent-relationships#many-to-many
CodePudding user response:
This is wrong!
You must have a users table
And a table groups
And a table:
user_group
Including :
user_id,group_id
$user = User::find(1);
$group = new Group; $group->name = "group 1";
$post = $user->group()->save($comment);