How to fix upsert problem when seeding? (laravel) - laravel

I have these code below, all seems working but when I try to run unit test it returns an error below.
Here is my seeder (this seeder is called many times in different test cases):
DB::table('sizes')->upsert([
[
'name' => 'jumbo',
'created_at' => date("Y-m-d H:i:s"),
'updated_at' => date("Y-m-d H:i:s"),
],
[
'name' => 'large',
'created_at' => date("Y-m-d H:i:s"),
'updated_at' => date("Y-m-d H:i:s"),
]
], ['id'], ['name']);
And the errors pops out:
Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 19 UNIQUE constraint failed: sizes.name (SQL: insert into "sizes" ("created_at", "name", "updated_at") values (2021-05-10 12:52:18, jumbo, 2021-05-10 12:52:18), (2021-05-10 12:52:18, large, 2021-05-10 12:52:18) on conflict ("id") do update set "name" = "excluded"."name")
Here is the migration:
Schema::create('sizes', function (Blueprint $table) {
$table->id();
$table->string('name')
->unique();
$table->timestamps();
});

Your migration will result in such table:
id INT AUTO_INCREMENT PRIMARY_KEY
name VARCHAR UNIQUE
created_at TIMESTAMP
updated_at TIMESTAMP
Your seeder when run first time will insert such records:
id
name
created_at
updated_at
1
jumbo
...
...
2
large
...
...
Now, based on laravel's documentation on upsert:
If you would like to perform multiple "upserts" in a single query, then you should use the upsert method instead.
The method's first argument consists of the values to insert or update, while the second argument lists the column(s) that uniquely identify records within the associated table.
The method's third and final argument is an array of the columns that should be updated if a matching record already exists in the database.
The upsert method will automatically set the created_at and updated_at timestamps if timestamps are enabled on the model:
The important point is:
The method's first argument consists of the values to insert or update,
while the second argument lists the column(s) that uniquely identify records within the associated table.
The method's third and final argument is an array of the columns that should be updated if a matching record already exists in the database
That means, your command:
DB::table('sizes')->upsert([
[
'name' => 'jumbo',
'created_at' => date("Y-m-d H:i:s"),
'updated_at' => date("Y-m-d H:i:s"),
],
[
'name' => 'large',
'created_at' => date("Y-m-d H:i:s"),
'updated_at' => date("Y-m-d H:i:s"),
]
], ['id'], ['name']);
Will do this:
check if any record have id of (blank) => no record will match (so upsert will become insert instead)
insert into database, value name=jumbo, and insert into database, value name=large,
this second step will fail since there's already record on database that have name=jumbo (and another record with name=large)
remember that you have name VARCHAR UNIQUE constraint, and this second step violates the UNIQUE constraint
Instead, you should change your seeder into this:
DB::table('sizes')->upsert([
[
'name' => 'jumbo',
'created_at' => date("Y-m-d H:i:s"),
'updated_at' => date("Y-m-d H:i:s"),
],
[
'name' => 'large',
'created_at' => date("Y-m-d H:i:s"),
'updated_at' => date("Y-m-d H:i:s"),
]
], ['name'], ['created_at','updated_at']);
The edited version will do this:
check if any record have name of "jumbo"
no record will match initially (so upsert will become insert first time),
and for subsequent run will match (so upsert will become update for subsequent runs)

Related

How to increment column with Laravel Eloquent updateOrCreate()?

Is it possible to return the model id from the request below ?
Bar::insert([
'foo_id' => Foo::updateOrCreate([
'code' => $row[0],
'name' => $row[1]
])->increment('count')->id
]);
I also tried this:
Foo::updateOrCreate([
'code' => $row[0],
'name' => $row[1]
], [
'count' => DB::raw('count + 1')
])->id
But it doesn't work at inserting because it count is not yet set.
HINT: There is a column named "count" in table "foos", but it cannot be referenced from this part of the query. (SQL: insert into "public"."foos" ("id", "name", "count") values (123, Hello, count+1) returning "id")
=== EDIT ===
With DB::raw('IFNULL(count,0) + 1'), I'm getting:
SQLSTATE[42703]: Undefined column: 7 ERROR: column "count" does not exist
LINE 1: ... ("code", "name", "count") values ($1, $2, IFNULL(count,0) +...
^
HINT: There is a column named "count" in table "foos", but it cannot be referenced from this part of the query. (SQL: insert into "public"."foos" ("code", "name", "count") values (123, Hello, IFNULL(count,0) + 1) returning "id")
Unfortunately I don't think this is possible to reference the count column only when the update happens (since this is what is happening here). You will need to take the roundabout way:
$model = Foo::firstOrNew([
'code' => $row[0],
'name' => $row[1]
]);
$model->count = ($model->exists ? $model->count : 0) + 1;
$model->save();
Here $model->exists will be true if the model was retrieved from the database or false if a new one was created.
Efficiency-wise firstOrCreate is what updateOrCreate does anyway so there's no query cost added
try using IFNULL
Foo::updateOrCreate([
'code' => $row[0],
'name' => $row[1]
], [
'count' => DB::raw('IFNULL(count,0) + 1')
])
if you want the id, try it like this:
$id=(Foo::updateOrCreate([
'code' => $row[0],
'name' => $row[1]
], [
'count' => DB::raw('IFNULL(count,0) + 1')
]))->id;
note: this is working on mysql, not PostgreSQL
you just need to set column auto-increment in database and not need set it column in your eloquent

Field 'id' doesn't have a default value when import excel file laravel

return new hasilsurvey([
'survey' => $row[1],
'question1' => $row[2],
'question2' => $row[3],
]);
I has setting my table columns 'id' to primary key but still get same problem
Please help my problem
When creating your migration you must define id field as autoincrement:
$table->bigIncrements('id');
If you want to update id field for that table you can do it with this:
$table->bigIncrements('id')->change();

How do I get a value of another table on Laravel?

I'm trying to get just value of id column on a table but it returns
SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '[{"id":1}]' for column 'id_jenis' at row 1 (SQL: insert into `pesanan` (`name`, `telpon`, `alamat`, `id_jenis`, `jenis`, `do`, `updated_at`, `created_at`) values (Pradita Candrani, 0813, Jalan Sunan Ampel Kasin, [{"id":1}], Cuci Basah Standar, None, 2019-11-27 12:18:35, 2019-11-27 12:18:35))
Here it is my code on Controller
public function pesan(Request $request){
$harga = Harga::select('id')->where('nama',$request->jenis)->get();
Pesanan::create([
'name' => $request->nama,
'telpon' => $request->telpon,
'alamat' => $request->alamat,
'id_jenis' => $harga,
'jenis' => $request->jenis,
'do'=>$request->do
]);
return redirect('/pesanan');
}
how can I fix this? Please help
You're getting object now and passing it to id_jenis directly. use first() instead of get(). and pass the $harga->id in id_jenis.
$harga = Harga::select('id')->where('nama',$request->jenis)->first();
Pesanan::create([
'name' => $request->nama,
'telpon' => $request->telpon,
'alamat' => $request->alamat,
'id_jenis' => $harga->id,
'jenis' => $request->jenis,
'do'=>$request->do
]);
If you want to store multiple ids in id_jenis then use pluck.
$harga = Harga::where('nama',$request->jenis)->pluck('id')->toArray();
Here you'll get multiple ids in array. so use json_encode to store JSON in db as below.
Pesanan::create([
'name' => $request->nama,
'telpon' => $request->telpon,
'alamat' => $request->alamat,
'id_jenis' => json_encode($harga),
'jenis' => $request->jenis,
'do'=>$request->do
]);
$harga = Harga::select('id')->where('nama',$request->jenis)->get();
After this line, write
\Log::info(['Harga', $harga]);
and check the latest file and error in /storage/logs/laravel.log
Welcome to the wonderful world of debugging

Laravel updateOrCreate with composite key

I have a table that's defined thus:
Schema::create('tableA', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('label_id')->unsigned();
$table->date('date');
$table->integer('value');
$table->unique(['user_id','label_id','date']);
$table->timestamps();
});
The table uses a composite key of user_id, label_id and date.
I would like to update the table using the Model::updateOrCreate method thus:
Model::updateOrCreate(
[
'user_id' => $user_id,
'label_id' => $label_id,
'date' => $date,
'value' => $value,
]);
But I get an error if I run the method when a row with the composite key already exists because it seems Laravel doesn't work with composite keys.
For example row
[
user_id:2,
label_id:3,
date:'2019-04-04',
value: 44
]
cannot be updated using
Model::updateOrCreate([
user_id:2,
label_id:3,
date:'2019-04-04',
value: 100
]);
Does this mean there's no way to use updateOrCreate and I need to check each row if it exists before I attempt to add it ?
If you want to update a row based on a user_id the first parameter of the updateOrCreate is an array of fields you are looking to match, and the second contains fields that should update. So from what you are saying I believe you should use this:
Model::updateOrCreate([
user_id => 2,
label_id => 3,
date => new Carbon('2019-04-04')
],
[
value => 100
]);

Automatically use Timestamp in Laravel 5.4 Query builder

is there any way to automatically use time-stamp when using query builder, currently I'm using CARBON.
here is my code:
DB::table('product_in_out')->insert(
['product_id' => $product_id,
'warehouse_id' => $warehouse_id,
'balance_before' => Product::getProductBalanceOf($action_id, $product_id),
'in' => $product_qty,
'out' => '0',
'after_balance' => Product::getProductBalanceOf($action_id, $product_id)+$product_qty,
'action' => 'ProcurementReceipt',
'action_id' => $action_id,
'created_by' => auth()->user()->id,
'updated_by' => auth()->user()->id,
'is_active' => '1',
'created_at' => \Carbon\Carbon::now(), # \Datetime()
'updated_at' => \Carbon\Carbon::now(),# \Datetime() ]
);
Fields created_at and update_at are part of Eloquent.
You need to use Eloquent instead of query builder to insert and update the record in to database for automatic time handling. Eloquent will handle auto update of updated_at column for you,
here is the way,
If you have model name Product,
$product = new Product();
$product->column_name = $column_value;
....
...
$product->save();
Above code will add time stamp automatically at created_at and updated_at column.
Now use Eloquent to update your records like,
$product = Product::find($id);
$product->update_column_name = $update_value;
...
...
$product->update();
This will update your updated_at column value accordingly.
Hope you understand.
Use Laravel Macros:
https://medium.com/fattihkoca/laravel-auto-save-timestamps-with-query-builder-without-using-eloquent-123f7ebfeb92
It is wise to create a macro to avoid typing the same things every time.
insertTs method inserting records into database with created_at data:
DB::table('users')->insertTs([
'email' => 'john#example.com'
]);
$id = DB::table('users')->insertGetIdTs([
'email' => 'john#example.com'
]);
updateTs method updating records into database with updated_at data:
DB::table('users')
->where('id', 1)
->updateTs(['email' => 'john#example.com']);
deleteTs method deleting records into database with deleted_at data (soft delete):
DB::table('users')
->where('id', 1)
->deleteTs();

Resources