I am trying to pass an array that has both existing and new rows I would like to insert into my QueueLane model by using laravel upsert function.
The code:
QueueLane::upsert([
['name' => 'Existing Lane Update', 'id' => 5],
['name' => 'A New Lane', 'id' => null]
], ['id'], ['name']);
You can see the first row has an id, so I want to update the name column with whatever value is in the array, the second row, however, doesn't have an id so I want this record to be created.
When running the code I get the following error:
null value in column "id" violates not-null constraint
I'm expecting the Laravel to populate the ID with a new auto incrementing integer as is the usual behavior for new records in the Model.
Related
I have a column type JSON in database, and I'm performing an update on multiple rows.
For example, this query
Model::whereIn('id',$ids)->update([
'status' => 'canceled'
]);
And this table has another column called history (JSON type), each row already has its own history in JSON.
How do I append to each one of them? This array, for example
[
'user_id' => '144',
'action' => 'cancel',
'at' => '2021 - 08 - 30'
]
My idea and question, is there something like
Model::whereIn( 'id', $ids )->appendJson('field_name',$array);
The easiest approach could be like this:
$status = 'canceled';
$extraHistoryData = [...];
Model::whereKey($ids)->get(function ($model) use ($status, $extraHistoryData) {
$history = $model->history;
$history = array_merge($history, $extraHistoryData);
$model->update(compact('status', 'history'));
});
If you want to update all rows in a single query, the closest I can get is this thread. But It's not very likely to solve your problem.
This table children table has relation with father table. So, if I update a record in "children table" for example name, then all name attribute records should be updated too.
DB::table('data_anak')->where('bapak_id', $id)->update([
'nama' => $request->nama_anak,
'jenis_kelamin' => $request->gender_anak,
'tempat_tgl_lahir' => $request->tmt,
'tgl_baptis' => $request->baptis_anak,
'tgl_sidi' => $request->sidi_anak,
]);
How do I do that?
Laravel 5.3, I have this 2 models:
User:
public function newFunctions()
{
return $this
->belongsToMany('App\NewFunctions', 'user_newfunctions')
->withPivot(['function_count', 'days_count']);
}
NewFunctions:
public function users()
{
return $this
->belongsToMany('App\User', 'user_newfunctions', 'new_function_id', 'user_id')
->withPivot(['function_count', 'days_count']);
}
I now how can I save new data to User, with this:
$user = User::findOrFail($id);
$user->name = $request->input('name');
$user->save();
But now I have to update some values of a pivot table. the pivot table is this:
user_id | new_functions_id | function_count | days_count
---------------------------------------------------------
814 | 1 | 5 |2019-07-19 12:26:19
814 | 3 | 7 |2019-07-19 12:26:19
I have more than 1 row per user_id. I was trying to use:
$user
->newFunctions()
->sync([
'days_count' => $test_date,
'function_count' => $test_int_number
]);
But I'm getting error like:
Ilegal offset type
because is trying to update with this:
array(
'records' => array(
'days_count' => object(Carbon), 'function_count' => '66'),
'results' => array(),
'id' => object(Carbon),
'attributes' => array()
)
)
in BelongsToMany.php
So:
How could I update the values for each user_id on the pivot table?
And how should use syncto update just 'function_count' and 'days_count'? they come from request.
->sync() isn't used like that; it's used to attach() and detach() related new_function_ids until only the ids in sync() are present. You're probably looking for updateExistingPivot()
An example of ->sync() would be using the array:
$user->newFunctions()->sync([
"new_function_id" => 1,
"function_count" => 6,
"days_count" => "2019-07-08 12:00:00",
]);
This would remove the record where new_function_id is 3, and updating the values where new_function_id is 1.
To update function_count and days_count for either new_function_id of 1 or 3, use ->updateExistingPivot() (pass the id you want to update as the first parameter):
$user
->newFunctions()
->updateExistingPivot("1", [
"function_count" => 6,
"days_count" = "2019-07-08 12:00:00"
]);
// or $user->newFunctions()->updateExistingPivot("3", ...);
This will update the pivot table where new_function_id is 1, while leaving the row where new_function_id is 3.
Edit: If you're looking to update all existing records in the pivot table, you'll need to do this in a loop, call a sync with all current records in a single array, or run a manual query.
Is it possible to update a timestamp (besides updated_at) and increment a column in one query? I obviously can
->increment('count')
and separately
->update(['last_count_increased_at' => Carbon::now()])
but is there an easy way to do both together.
Product::where('product_id', $product->id)
->update(['count'=> $count + 1, 'last_count_increased_at' => Carbon::now()];
Without having to query and get the count first?
You can specify additional columns to update during the increment or decrement operation:
Product::where('id',$id)
->increment('count', 1, ['increased_at' => Carbon::now()]);
It is more eloquent solution.
You can use the DB::raw method:
Product::where('product_id', $product->id)
->update([
'count'=> DB::raw('count+1'),
'last_count_increased_at' => Carbon::now()
]);
With Laravel 8 you can now achieve this in a single query to create or update on duplicate key.
$values = [
'name' => 'Something',
'count' => 1,
];
$uniqueBy = ['name'];
$update = ['count' => DB::raw('count+1')];
Model::upsert($values, $uniqueBy, $update);
If the model exists count will be incremented, if it is inserted count will equal 1. This is done on the DB level, so only one query involved.
Read more about upserts: https://laravel.com/docs/8.x/eloquent#upserts
I'm new in WordPress
I'm trying to insert on database without knowing the id, here what I'm trying to do:
$create = $wpdb->insert('wp_ito_plan', array('name' => $_POST['name'], 'tickets' => $_POST['tickets'], 'price' => $_POST['price'], 'visits' => $_POST['visits']));
and I got this error:
WordPress database error: [Duplicate entry '0' for key 'PRIMARY']
INSERT INTO `wp_ito_plan` (`name`,`tickets`,`price`,`visits`) VALUES ('asd','123','123','123')
I tried adding to the array: 'id' => $wpdb->insert_id, but stills the same.
How can I fix this? Do I need to check what is the last ID on database and then increment? There's no easiest way?
It appears as though you aren't auto incrementing the ID column so you're insert is going to overwrite an existing row. Set the ID column to auto increment and it should work fine.