Support the ongoing development of Laravel.io →
Laravel
0

Hello caiosalchesttes,

There is an example of a regular sql statement that has an auto increment row

INSERT INTO `posts` (`id`, `text`) VALUES (NULL, 'I am Akpevwe Jenkins.');
 

If you notice, the value for the 'id' here is NULL because it is an auto-incremented value. I think if you provide null for the 'id' column in the second array, Laravel will simply ignore the null value and rely on the database to handle the auto-incrementing behavior for the 'id' column as usual. So, your code will look like this:

DatasetLabel::upsert(
    [
        ['id' => 4, 'name' => 'A', 'tenant_id' => 1, 'dataset_id' => 1],
        ['id' => null, 'name' => 'B', 'tenant_id' => 1, 'dataset_id' => 1]
    ],
    uniqueBy: ['id'],
    update: ['name']
);

Do let me know if it worked. All the best.

Last updated by @jenkins 1 month ago.
0

So when I do this, I get the following error:

SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "id" of relation "dataset_labels" violates not-null constraint DETAIL: Failing row contains (null, 1, B, null, 0, 1, null, 2024-05-25 19:33:41, 2024-05-25 19:33:41).

Since it doesn't accept the null table, the only way would be to create a random ID, but I believe that this upsert function wouldn't be fulfilling the role assigned by Laravel. I think this would be an error, right?

0

Hello caiosalchesttes, I just tried it on my end , and it worked for me.

As for this error: Failing row contains (null, 1, B, null, 0, 1, null, 2024-05-25 19:33:41, 2024-05-25 19:33:41).

Please check your database if the ID colume is on auto increment.

on the other hand, it is advisable to have more than one uniqueBy colume Here is an example

<?php
//Tinker away!
use App\Models\User;
 User::upsert( [
    ['id' => 4, 'first_name' => 'c', 'last_name' => 1, 'email' => '[email protected]', 'password'=>'akpevwe'],
    ['id' => null, 'first_name' => 'z', 'last_name' => 1, 'email' => 11, 'password'=>'akpevwe']
],
    uniqueBy: ['id','email'],
    update: ['first_name']);
Last updated by @jenkins 1 month ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.