How can I use UPDATE or INSERT with Laravel 4?

I am building an application in Laravel 4 and I need to run multiple queries as UPDATE or INSERT queries to avoid PK violations for duplicate inserts. I could not find a way to do this using the query builder in Laravel.

Is it possible to change the DB class or something like that? Or do I just need to write pure SQL statements?

+4
source share
3 answers

Now we can use User::updateOrCreate()

+11
source

You can use the DB :: operator. http://laravel.com/docs/database

  DB::statement('INSERT INTO comments (comments) values (?)', array('LOL')); 

You can add DUPLICATE KEY UPDATE there.

Unfortunately, there is no way to do this (which I know) with eloquent unless you do something like

  $user = User::find(1); if ($user === null) { $user = new User; } $user->name = 'hey'; $user->save(); 
+9
source

It would be nice if Fluent supported ON DUPLICATE KEY UPDATE or INSERT IGNORE, but that doesn't seem to be the case. The closest solution I found is to use firstOrCreate () for your model.

 User::firstOrCreate( array('id'=>1, 'name'=>'hey') ); 

This can do what you need without writing out the full request in some scenarios.

+4
source

Source: https://habr.com/ru/post/1488250/


All Articles