简体   繁体   English

使用 Eloquent 插入和更新基于多行的外键的最佳方法是什么?

[英]What is the best approach for insert and update multiple rows based foreign key using Eloquent?

I have a table named 'answers' which will store customer answer about questionnaire.我有一个名为“answers”的表,它将存储客户对问卷的回答。 The table looks like this桌子看起来像这样

answers
+-----------------+
|id (PK)          |
|customer_id (FK) |
|question_id (FK) |
|value            |
|_________________|

my request would be like this我的要求是这样的

{
    "customer_id":1,
    "answer": {
        "1":"My Name", //"1" is question_id , "My Name" is value
        "2":"My Phone Number" //"2" is question_id, "My Phone Number" is value
    }
}

What i'm trying to achieve is doing a single query or single action on Eloquent instead of foreach the answer one by one to check if the question_id and customer_id already exists it will update otherwise it will insert the answer to table 'answers'.我想要实现的是在 Eloquent 上执行单个查询或单个操作,而不是一个一个的 foreach 答案来检查question_idcustomer_id 是否已经存在,否则它将更新,否则它会将答案插入表 'answers'。

By doing foreach/looping one by one per answer data, it shouldn't be a hard problem.通过对每个答案数据一个一个地进行 foreach/循环,这应该不是一个难题。 However if i already got 3000++ rows in 'answers' table then it would be a big problem.但是,如果我在“答案”表中已经有 3000++ 行,那么这将是一个大问题。

What is the best approach to do this?做到这一点的最佳方法是什么? Maybe is there any third-party library that i can use to do Mass Insert/Updates multiple rows based on foreign key check?也许有任何第三方库可以用来根据外键检查批量插入/更新多行?

You can do this by laravel's UpdateORCreate Method which do the exact thing that you want.你可以通过 laravel 的UpdateORCreate方法来做到这一点,它可以做你想做的事情。

In General the statement is like below:一般来说,声明如下:

$model=Model::UpdateOrCreate(["condtion1"=>"value1",...],["field1"=>"value1",...]);

In your case it'll be something like below:在您的情况下,它将类似于以下内容:

$answer=Answer::UpdateOrCreate(["customer_id"=>$customer_id,"question_id"=>$question_id],["value"=>$value]);

For more information, Check Laravel Eloquent Documentation (Other Creation Methods)有关更多信息,请查看Laravel Eloquent 文档(其他创建方法)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM