当前位置:网站首页>Some query constructors in laravel (2)

Some query constructors in laravel (2)

2022-07-05 01:45:00 phpstory

310 piece
One 、upsert Method is used to insert a nonexistent record , And update the existing record with the new value you specify . The first parameter of the method consists of the value to be inserted or updated , The second parameter lists the columns that uniquely identify the records in the associated table . The third and last parameter of this method is a column array , If a matching record already exists in the database , Then these columns should be updated :

DB::table('flights')->upsert([
    ['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],
    ['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]
], ['departure', 'destination'], ['price']);

In the example above ,Laravel Will try to insert two records , If the record exists with departure and destination Column with the same value ,Laravel Will update price The value of the column .

Two 、 Sometimes you may want to update existing records in the database , Or if there is no matching record, create it . under these circumstances , have access to updateOrInsert Method . updateOrInsert Method accepts two arguments : An array of conditions for finding records , And an array of key value pairs containing the record to be updated .

updateOrInsert Method will first try to find a matching database record using the key and value pairs of the first parameter . If records exist , Then use the value in the second parameter to update the record . If no record is found , A new record will be inserted , The new data is a collection of two arrays :

DB::table('users')
    ->updateOrInsert(
        ['email' => '[email protected]', 'name' => 'John'],
        ['votes' => '2']
    );

3、 ... and 、 to update JSON A field , You can use -> Grammar access JSON Object . Be careful , This operation can only be supported MySQL 5.7+ and PostgreSQL 9.5+ :

$affected = DB::table('users')
              ->where('id', 1)
              ->update(['options->enabled' => true]);
 notes : If your field is json, You can update a certain attribute value ,options yes users Fields in the table ,enabled Is a value inside , for example :options The value in it is {
    "name": "phpstory", "enabled": true}, You can modify the inside enabled value               
原网站

版权声明
本文为[phpstory]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202141016247171.html