1
I have a person registration system and there is an area with several checkbox fields that represent the social group that the current person represents:
TABLES
person
id | nome
1 | João
2 | Maria
3 | Ana
group
id | grupo
1 | Lorem1
2 | Lorem2
3 | Lorem3
group person
id | id_grupo | id_pessoa
1 | 1 | 1
2 | 1 | 2
3 | 2 | 1
And I have the following code in my controller to save the changes:
Personal controller
$grupo = $request->grupo; //retornando valores dos campos checkbox
for($x = 0; $x < count($grupo); $x++){
array_push($query_grupo, array('id_grupo' => $grupo[$x], 'id_pessoa' => $id));
}
DB::table('grupo_pessoa')->insert($query_grupo);
I need to remove from the table the groups I uncheck and save the selected ones only if they don’t exist yet.
I tried using "save" because they say it already does this check but it didn’t work the way I tried:
$grupo_pessoa = new GrupoPessoa;
for($x = 0; $x < count($grupo); $x++){
$grupo_pessoa->id_grupo = $grupo[$x];
$grupo_pessoa->id_pessoa = $id;
$grupo_pessoa->save();
array_push($query_grupo, array('id_grupo' => $grupo[$x], 'id_pessoa' => $id));
}
Do you know Sync or attach e dettach? Here’s what you’ll find... https://laravel.com/docs/5.2/eloquent-relationships#inserting-Many-to-Many-relationships if I can’t make a model later today. Abs
– Evert
Never used and it’s very complex kkkk I’ll see if I understand.
– Kelvym Miranda
It’s quiet, in fact. your link table doesn’t need id, it can only have the two keys of the person and group table both as the primary key and will be even faster the search. Do a simple test first and you will see that it is very simple. I have something ready, but I could not find it here. I will send you a ready example later. Abs
– Evert
That’s what João’s answer is. I couldn’t finish it... but I will do it soon to stay as a reference, it follows: https://github.com/code-sample/laravel-many-to-many I must finish hj the night or tomorrow. I have to do the views... if you want to help. Abs
– Evert