4
I have a table called agenda
, among the fields of this agenda it is possible to add several responsible for it, which are the users registered in the system, for this there is a field of type multiple select
, which allows you to select multiple user Ids, and to save these various "responsible", I created a table called agenda_responsaveis
, that saves agenda id (agenda_id
) and the id of each user (user_id
).
Currently, when creating the schedule, to save the responsible ones, I traverse the data of select with a foreach and insert the data in the table agenda_responsaveis
Ex:
$create = Agenda::create($data);
foreach ($request->responsavel_id as $key => $id) {
AgendaResponsavel::create(array(
'agenda_id' => $create->
'user_id' => $id
));
}
And in the editing part of the agenda, I search all the records with the agenda_id
, I delete the old data and re-enter the new data coming from select. I do this because I don’t have the id of each record in the table agenda_responsaveis
.
Ex:
AgendaResponsavel::where('agenda_id', $agenda_id)->delete();
foreach ($request->responsavel_id as $key => $id) {
AgendaResponsavel::create(array(
'agenda_id' => $agenda_id,
'user_id' => $id
));
}
would you like to know if there is a more efficient way to do this? without seeming a "gambiarra"
You need to have the relationship on the App User as well?
– Thiago
It is not necessary. But if you want to return the schedules or insert in the pivot table from the User ai model you create. Let’s say you want to take the schedules of a responsible person:
$user = User:find($id);
$agendas = $user->agendas;

. Anyway, if you don’t need to manipulate the data through the other model, you don’t need to create.– Ryan Lemos