laravel sync() equivalent for OneToMany relation

359 views Asked by At

i want to know what is the best practice to update a relationship, like the sync() methode for many to many relations.

i have a one to many relation like that :

One question can have multiple responses, and one response can be only for one question

The user is able to change responses for each question, add more responses, or delete some, (by using javascript) or modify it in the Edit page input.

In the QuestionsController@update i get responses like that :

array:7 [▼
  0 => "first response"
  1 => "second"
  2 => "third"
]

(depending on the number of questions that the user sent, it can be more or less)

I thought I could do :

$question = Question::findOrFail($id);
$responses = $request->get('responses');
$question->responses()->sync($responses);

but it only works for many to many relations... so i do that :

$question = Question::findOrFail($id);
foreach($request->get('responses') as $response){
    $responses[] = new Response(['content' => $response]);
}
$question->responses()->delete();
$question->responses()->saveMany($reponses);

what do you think about that ? it works but i have a doubt that this is the best thing to do

thanks

0

There are 0 answers