I have below foreach loop, which iterates over a bunch of different custom rules my users can apply.
public function parse(Document $document)
{
$content = $document->text;
$rules = $document->stream->fieldrules;
foreach ($rules as $rule) {
$class = $this->getClass($rule);
$content = $class->apply($content);
//Save to database.
$fieldresult = new FieldRuleResult();
$fieldresult->create([
'field_rule_id' => $rule->field_id,
'document_id' => $document->id,
'content' => $content
]);
}
}
As you can see, I am calling the database on each iteration. Some users may have up to 50 rules defined, which will then result in 50 insert queries. So I believe I may have encountered a n+1
problem.
I was wondering - what is the best practice here? I've tried searching the Laravel documentation, and found the createMany
method. So I tried to refactor the iteration to below:
$result = [];
foreach($rules as $rule)
{
$class = $this->getClass($rule);
$content = $class->apply($content);
$fieldresult = new FieldRuleResult();
$result[] = [
'field_rule_id' => $rule->field_id,
'document_id' => $document->id,
'content' => $content];
}
return $rules->createMany($result);
Which gives me below error:
Method Illuminate\Database\Eloquent\Collection::createMany does not exist.
Now I imagine that is because $rules
returns a collection. I tried to alter it to:
return $document->stream->fieldrules()->createMany($result);
Which gives me below error:
Call to undefined method Illuminate\Database\Eloquent\Relations\HasManyThrough::createMany()