简体   繁体   中英

Laravel update a null value or ignore, or insert if reference key don't exist

I have a question about insertOrIgnore method, in the last time I used upsert method to update or create a new row on my database structured like this:

id name surname
2 "foo" "bar"
4 null "vel"

With upsert , I'm able to update the name with id = 4 , but doing something like this:

DB::table('funnypeople')->insertOrIgnore(
  ['id' => 4, 'name' => "lara"]
);

He don't change the name from null to "lara"

There's something similar to update a value if is null but not update if is already set?

Other case, if I would like to add id if not exist and save all the value

DB::table('funnypeople')->insertOrIgnore(
  [
   'id' => 4, 'name' => "lara",
   'id' => 6, 'name' => "fancy", 'surname' => 'people'
]);

The resulting table should be:

id name surname
2 "foo" "bar"
4 "lara" "vel"
6 "fancy" "people"

I tried olso to pass the reference column like in upsert but it add only the new row on the table:

DB::table('funnypeople')->insertOrIgnore(
  [
   'id' => 4, 'name' => "lara",
   'id' => 6, 'name' => "fancy", 'surname' => 'people'
],'id');
id name surname
2 "foo" "bar"
4 null "vel"
6 "fancy" "people"

From laravel docs:

The insertOrIgnore method will ignore errors while inserting records into the database:

DB::table('users')->insertOrIgnore([
    ['id' => 1, 'email' => 'sisko@example.com'],
    ['id' => 2, 'email' => 'archer@example.com'],
]);

insertOrIgnore will ignore duplicate records and also may ignore other types of errors depending on the database engine. For example, insertOrIgnore will bypass MySQL's strict mode.

for insert or update you need this:

Occasionally, you may need to update an existing model or create a new model if no matching model exists. Like the firstOrCreate method, the updateOrCreate method persists the model, so there's no need to manually call the save method.

$flight = Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99, 'discounted' => 1]
);

more info in official Laravel doc

In your code example you are using insertOrIgnore instead of upsert . insertOrIgnore don´t update just insert ignoring errors, in you case can´t insert the id 4 because primary key fails but was ignored and continue to insert ID 6

DB::table('funnypeople')->insertOrIgnore(
  [
   'id' => 4, 'name' => "lara", //Fail because PK exist in DB
   'id' => 6, 'name' => "fancy", 'surname' => 'people' //Continue inserting this
]);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM