gpt4 book ai didi

php - Laravel Multi Insertion 及其关系

转载 作者:行者123 更新时间:2023-11-29 10:42:47 28 4
gpt4 key购买 nike

我知道 Model::insert() 但它的关联关系怎么样?

我们知道表单提交后可以有 100 个问题,但相应的问题大约有 4 个答案(对于多项选择题)

我们的问题数据如下所示

$question = [
'1' =>[
'name'='Who is first president of America'?
...
]
...
'100' =>
'name' = 'When did Christopher Colombus discovered America'
....

...
]

$answers = [
'1'=>
[
'1' => 'Wilston Churcil',
'2' => 'George Washinton'
....
]
...
...
]

$correct_answer = [
'1'=>['2']
...
]

关系

  • 问题有很多答案
  • 问题有很多正确答案

我们正在尝试一次上传许多问题

我们可以清楚地看到,如果我们不使用 laravel create,否则我们将运行 n+1 个问题,对于 100 个问题,我们可能需要 100 + 400 + 100 个查询,这是非常低效的?

如果 Question::insert() 返回了插入问题的 id 那么这很容易,但它只返回 bool 值..

是否有办法在不使用 n+1 问题的情况下解决此类问题。

我尝试使用 n+1 和后台作业,但它确实非常慢:(

任何解决方案和黑客都可以:(

最佳答案

hasMany(..)->saveMany([$array]) 方法仅运行 1 个查询来保存 $array 内的所有对象。不过,您仍然需要迭代所有答案。

foreach($questions as $key => $question) {
$answerArray = []
foreach($answers[$key] as $answer) {
$answerArray[] = new App\Answer($answer[1], $answer[2], $answer[3], ...)
}
$q = new App\Question($question['name'], ....);
$q->save();
$q->answers()->saveMany($answerArray);
}

如果这仍然太慢,我认为您唯一的选择是创建一个作业来将数据保存在不同的任务中( Official docs about jobs ),因此网络请求不需要等到所有数据都保存完毕.

关于php - Laravel Multi Insertion 及其关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45170447/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com