ON DUPLICATE KEY UPDATE in Eloquent

前端 未结 2 1743
终归单人心
终归单人心 2021-01-18 18:53

I just started laravel and all I want to do is get following query working in Eloquent:

INSERT INTO geschichte (geschic         


        
相关标签:
2条回答
  • 2021-01-18 19:15

    Most of what is in your controller should not be necessary. I am also a little concerned about the database structure you are using as to why you would perform a task like shown in your controller. The following should be all you need:

    public function alterGeschichte(Request $request)
    {
        Geschichte::updateOrCreate(
           ['id' => 1],
           ['id' => 1, 'geschichte_text1' => $request->geschichte_text1]
        );
    
        Geschichte::updateOrCreate(
           ['id' => 2],
           ['id' => 2, 'geschichte_text2' => $request->geschichte_text2]
        );
    
        Geschichte::updateOrCreate(
           ['id' => 3],
           ['id' => 3, 'geschichte_text3' => $request->geschichte_text3]
        );
    
        return redirect('/geschichte');
    }
    

    If these are creating new records it is most likely because there is no record with those ID's.

    0 讨论(0)
  • 2021-01-18 19:23

    Looks like you don't have a unique key setup on the columns you wish to be unique. In order to use on duplicate key update, you will need that so your database server will know if it needs to insert or update.

    Unfortunately, Laravel doesn't have support for on duplicate key update syntax. This would be useful because it tries to insert and if it's already in the table, then it will update the columns accordingly in one query.

    Using Laravel's updateOrCreate method, it first queries the table to see if it needs to generate an insert or update statement and then proceeds accordingly. You don't get the advantage of running just one query but at the same time, it's Laravel which is handling all the extra logic so it's a slight trade-off.

    0 讨论(0)
提交回复
热议问题