duangongqiong6958 2019-02-09 12:17
浏览 79

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

I have a table named 'answers' which will store customer answer about questionnaire. 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'.

By doing foreach/looping one by one per answer data, it shouldn't be a hard problem. However if i already got 3000++ rows in 'answers' table then it would be a big problem.

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?

  • 写回答

1条回答 默认 最新

  • dougu2006 2019-02-09 16:11
    关注

    You can do this by laravel's UpdateORCreate Method which do the exact thing that you want.

    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)

    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100