Laravel Eloquent update multiple rows with same value but different ID - php

I'm using Laravel 6 and Eloquent. I'm looking for a way to update a set of rows with a set value, each identified with a unique ID.
This is what I'm doing right now:
$ids = [3948, 1984, 7849, 4456, 394];
$value = false;
foreach ($ids as $id)
{
User::where("id", $id)->update(["status" => $value]);
}
Is there a way to accomplish the same with only 1 query instead of 5?

You can use whereIn, like:
$ids = [3948, 1984, 7849, 4456, 394];
$value = false;
User::whereIn("id", $ids)->update(["status" => $value]);

Related

How to filter child table selected using with clause in laravel

I am querying Item using following:
$itemdata = Item::with('itemimagedetails')
->with('variation')
->select('item.id', 'item.cat_id', 'item.item_name', 'item.item_description', 'item.brand', 'item.manufacturer', 'item.country_origin', 'item.ingredient_type', 'item.delivery_time', 'categories.category_name', 'item.category_unit')
->join('categories','item.cat_id','=','categories.id')
->where('item.id', $request['item_id'])->get()->first();
I want to filter variations using planid fetched from user table.
$plan = User::where('id', $request['user_id'])
I have tried:
if (count($itemdata->variation) > 0) {
$plan = User::where('id', $request['user_id'])->get();
foreach ($itemdata->variation as $key => $tag_name) {
if($tag_name == $plan['plan_id']) {
unset($itemdata->variation[$key]);
}
}
}
But then I get an error in the API calls.
Can someone please suggest best approach?
try using "having" statement search it in in laravel docs

How can i update one row usign two keys in laravel?

I have a need to update a table like this :
UPDATE table SET column = value WHERE first_id = 1 AND second_id = 2
Is it possible to do this in Laravel using eloquent model? If it is how can i do this?
I was trying with :
$object = Model::where('first_id' , 1)->where('second_id' , 2)->get();
$object->column = $value
$object->save();
Yes you can do it. Here is how you can do it.
Model::where('first_id', 1)
->where('second_id', 2)
->update(['column' => 'yourValue']);
You are getting a collection. You can update the column of each of those collection. You can only get the first one collection using first.
foreach($object as $obj){
$obj->column = $value;
$obj->save();
}
Or
$object = Model::where('first_id' , 1)->where('second_id' , 2)->first();
$obect->column =$value;
$object->save();

How to updated multiple records with Laravel and Eloquent?

I have a project written using PHP on the top of Laravel 5.7. I am using Eloquent ORM to interact with the database.
I need to be able to update lots of records after pulling them from the database.
Here is how I am trying to do it.
$records = Record::where('Key','Test')->get();
$values = collecT([
['Id' => 1, 'Col' => 100],
['Id' => 2, 'Col' => 200],
['Id' => 3, 'Col' => 500],
....
]);
foreach($records as $record) {
$newValue = $values->where('Id', $record->id)->first();
if(is_null($newValue)){
continue;
}
$record->ColName = $newValue['Col'];
$record->save();
}
The above code does not write the updated value to the database. However, if I do the following it gets updated
foreach($values as $value) {
$record = Record::where('Key','Test')->where('id', $value['Id'])->first();
if(is_null($record)){
continue;
}
$record->ColName = $value['Col'];
$record->save();
}
Although the above code works, I have to make 1 select + 1 update statement for every record in the $values array. If the size of $values array is 1000. That's going to generate up to 2000 queries which are insane!
How can I correctly update multiple records in the database without doing range-update.
If all the rows you are trying to update would get the same value it is an easy problem. The problem becomes a bit more tricky because all your rows need to be updated with different values. This comment on a github issue of laravel has a solution that will do it with a single query, allowing him in that case with a 13x performance boost for 1000 rows to be updated compared to updating them one by one:
public static function updateValues(array $values)
{
$table = MyModel::getModel()->getTable();
$cases = [];
$ids = [];
$params = [];
foreach ($values as $id => $value) {
$id = (int) $id;
$cases[] = "WHEN {$id} then ?";
$params[] = $value;
$ids[] = $id;
}
$ids = implode(',', $ids);
$cases = implode(' ', $cases);
$params[] = Carbon::now();
return \DB::update("UPDATE `{$table}` SET `value` = CASE `id` {$cases} END, `updated_at` = ? WHERE `id` in ({$ids})", $params);
}
You can also try https://github.com/mavinoo/laravelBatch which does something similar.

Update order in pivot table when using sync in Laravel

In Laravel 4.2, I have the following code:
$thingIds = [];
foreach ($this->things as $thing) {
$thingIds[] = $thing->id;
}
$thong->things()->sync($thingIds);
$thong->save();
Which seems to work for me, however in my pivot table I have an order column that isnt being updated/synced correctly. The order is set to 1 for each item in the pivot table, however I want the order to be representative of the order of the ids in $thingIds.
Is this possible?
Is it possible to update an additional column in the pivot table using ->sync()?
After the suggestion in the comments, I have also tried the following code:
$thingIds = [];
foreach ($this->things as $index => $thing) {
$thingIds[$thing->id] = ['order' => $index];
}
$thong->things()->sync($thingIds);
$thong->save();
And I have tried
$thingIds = [];
$order = [];
foreach ($this->things as $index => $thing) {
$thingIds[] = $thing->id;
$order[] = ['order' => $index];
}
$thong->things()->sync(array_combine($thingIds, $order));
$thong->save();
But neither of these is working (the order is still 1 for each item in the pivot table). Can anyone explain what I am doing wrong?
If I do the attaching one at a time, like so:
foreach ($this->things as $index => $thing) {
$thong->things()->attach($thing, ['order' => $index]);
}
The order comes out correctly in the pivot table. How can I get the same effect but whilst still using ->sync()?

Laravel 5 - Change all values in a Column of a table

I have a table with column called "estado" and I want change all the column in one shot.
This is the right method? The faster one?
$vendedor = Vendedor::with('produtos')->find( $idVendedor );
foreach ( $vendedor->produtos as $produto ) {
$produto->pivot->estado = $novoEstado;
};
The column what I want change is "estado". There's a way to do it without the foreach?
Update Specific column you want to upadate using Laravel eloquent.
Way -> 1
[Status-> Column you want to update]
Model::where('status', '=', 1)->update(['status' => 0]);
Way -> 2
[Status-> Column you want to update]
$allData = Model::where('status', 1)->get();
foreach ($allData as $data){
$data->status = 0;
$data->update();
}
The simplest would be to just use the query builder for this (instead of your model)
DB::table('table_name')->where('vendedor_id', $idVendedor)->update('estado', $novoEstado);

Categories