createMany on createMany in Laravel?

Viewed 2863

So, I have 2 one to many relationship, first is questionnaire and question where question is belongsTo questionnaire. And the second one is question and answer where answer is belongsTo question. I have 2 arrays that look like this:

$questionData = [
    ['question' => 'Question 1'],
    ['question' => 'Question 2']
];

$answerData = [
   ['answer' => 'Good'],
   ['answer' => 'Meh']
];

Basically, what I'm trying to do is insert the $questionData first using createMany method and then followed by $answerData so my answer table will kinda look like this:

id   question_id   answer
1    1             Good
2    1             Meh
3    2             Good
4    2             Meh

I've tried with something like this:

$question = $questionnaire->question()->createMany($questionData);
$question->answer()->createMany($answerData);

And it gave me Method Illuminate\Database\Eloquent\Collection::answer does not exist. error. Any idea on how to achieve it?

1 Answers

createMany returns an iterable (in this case an array) of all of the objects that were created. In your case it will return an array containing all of the questions it created.

You can loop through each of them using forEach and call createMany on each of them:

$questions = $questionnaire->question()->createMany($questionData);
foreach ($questions as $question) {
   $question->answer()->createMany($answerData);
}
Related