I'm building an application in Laravel 4 and I need to run several queries as UPDATE OR INSERT queries to avoid PK violations on duplicate inserts. I haven't been able to find any way to do this with the query builder in Laravel.
Can I modify the DB class or something similar? Or will I need to just write pure SQL statements?
现在我们可以使用User::updateOrCreate()
You can use DB::statement. http://laravel.com/docs/database
DB::statement('INSERT INTO comments (comments) values (?)', array('LOL'));
You can put ON DUPLICATE KEY UPDATE in there.
There's unfortunately no way to do it (that I know of) with eloquent unless you do something like
$user = User::find(1);
if ($user === null) {
$user = new User;
}
$user->name = 'hey';
$user->save();
It would be very nice if Fluent support ON DUPLICATE KEY UPDATE or INSERT IGNORE but it doesn't seem to. The closest solution I found was to use firstOrCreate() on your model.
User::firstOrCreate( array('id'=>1, 'name'=>'hey') );
This may do what you need without writing out the full query in some scenarios.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.