Connect 2 queries to 1 - php

I have code like this:
$id = 5;
$a = 1;
$b = ($a === 2 ? 1 : 2);
DB::table('table')->where('id', $id)->where('value', $a)->update(['new_value' => 1]);
DB::table('table')->where('id', $id)->where('value', $b)->update(['new_value' => 2]);
Is it possible to make this 2 queries in 1?

You cannot use the query builder for this. Use DB::statement instead:
DB::statement('UPDATE table SET new_value = CASE
WHEN value = ? THEN ?
WHEN value = ? THEN ?
END WHERE id = ?', [
$a, 1,
$b, 2,
$id,
]);

In mysql query you can achieve by below query:
$mysqlQuery = "UPDATE table1
SET new_value = IF(id=".$id ." AND value=".$a.",1, IF(id=".$id." AND value=".$b.",2,new_value))";
Note:If you want this mysql query to be written in some framework specific query then you can convert it as per your framework syntax or documentation.

AFAIK, not with laravel fluent. There are 2 different queries with different update values. You can however make it into a reusable function.
public function updateNewValue($id, $value, $newValue)
{
return DB::table('table')
->where('id', $id)
->where('value', $value)
->update(['new_value' => $newValue]);
}
Or, you can combine it into one with a switch statement depending on the new_value:
$query = DB::table('table')->where('id', $id);
switch($newValue)
{
case 1:
return $query->where('value', $a)->update(['new_value' => $newValue]);
case 2:
return $query->where('value', $b)->update(['new_value' => $newValue]);
}

Related

Laravel Eloquent update multiple rows with same value but different ID

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]);

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.

how to use like operator in array laravel 5.2?

I want to add Like operator in array but it gives me error:
Unknown column '0' in 'where clause (admin_id = 2 and 0 = name and Like = %zdgbdsh%) order by id asc limit 10 offset 0)
Here is my query:-
$conditions = array();
if(!empty($data['name'])) {
$conditions = array_merge($conditions,array('name','Like'=>'%'.$data['name'].'%'));
}
And here is my final query:-
$querys = DB::table('users')
->where($conditions)
->skip($iDisplayStart)->take($iDisplayLength)
->OrderBy($orderby,$dir)
->get();
Note: I don't want directly in query like
where('users.name','like','%'.$data['name'].'%');**
I want to do in conditions variable
I am using laravel framework 5.2
It should be:
$conditions=array_merge($conditions,array('name' => 'Like %'.$data['name'].'%'));
Update
I've just realised that will produce name = Like %data%
You can change it to:
$conditions=array_merge($conditions,array('name', '%'.$data['name'].'%'));
and in where use:
->where(join(' LIKE ', $conditions))
This is not the greatest way of applying multiple conditions, But you can always user the whereRaw
so loop through a array with your conditions eg.
$conditions = [];
if (!empty($data['name'])) {
$conditions = array_merge(
$conditions,
["name LIKE '%".$data['name']."%'"]
);
}
$query = DB::table('users');
// apply add raw conditions
foreach($conditions as $condition){ $query->whereRaw($condition); }
$query->skip($iDisplayStart)->take($iDisplayLength)
->OrderBy($orderby,$dir)
->get();
you could also find some packages that will help you out with things like this.
Hope it helps

Laravel Eloquent orWhere Query

Can someone show me how to write this query in Eloquent?
SELECT * FROM `projects` WHERE `id`='17' OR `id`='19'
I am thinking
Project::where('id','=','17')
->orWhere('id','=','19')
->get();
Also my variables (17 and 19) in this case are coming from a multi select box, so basically in an array. Any clues on how to cycle through that and add these where/orWhere clauses dynamically?
Thanks.
You could do in three ways. Assume you've an array in the form
['myselect' => [11, 15, 17, 19], 'otherfield' => 'test', '_token' => 'jahduwlsbw91ihp'] which could be a dump of \Input::all();
Project::where(function ($query) {
foreach(\Input::get('myselect') as $select) {
$query->orWhere('id', '=', $select);
}
})->get();
Project::whereIn('id', \Input::get('myselect'))->get();
$sql = \DB::table('projects');
foreach (\Input::get('myselect') as $select) {
$sql->orWhere('id', '=', $select);
}
$result = $sql->get();
The best approach for this case is using Laravel's equivalent for SQL's IN().
Project::whereIn('id', [17, 19])->get();
Will be the same as:
SELECT * FROM projects WHERE id IN (17, 19)
This approach is nicer and also more efficient - according to the Mysql Manual, if all values are constants, IN sorts the list and then uses a binary search.
In laravel 5 you could do it this way.
$projects = Projects::query();
foreach ($selects as $select) {
$projects->orWhere('id', '=', $select);
}
$result = $projects->get();
This is very useful specially if you have custom methods on your Projects model and you need to query from variable. You cannot pass $selects inside the orWhere method.
public function getSearchProducts($searchInput)
{
$products = Cache::rememberForever('getSearchProductsWithDiscountCalculationproducts', function () {
return DB::table('products_view')->get();
});
$searchProducts = $products->filter(function ($item) use($searchInput) {
return preg_match('/'.$searchInput.'/i', $item->productName) || preg_match('/'.$searchInput.'/i', $item->searchTags) ;
});
$response = ["status" => "Success", "data" => $searchProducts ];
return response(json_encode($response), 200, ["Content-Type" => "application/json"]);
}
use filter functionality for any customize situations.

Laravel whereIn OR whereIn

I'm making a products search by filters:
My code:
->where(function($query) use($filter)
{
if(!empty($filter)){
foreach ($filter as $key => $value) {
$f = explode(",", $value);
$query-> whereIn('products.value', $f);
}
}
})
Query:
and (products.value in (Bomann, PHILIPS) and products.value in (red,white))
But I need:
and (products.value in (Bomann, PHILIPS) OR products.value in (red,white))
Is there something similar in Laravel:
orWhereIn
You could have searched just for whereIn function in the core to see that. Here you are. This must answer all your questions
/**
* Add a "where in" clause to the query.
*
* #param string $column
* #param mixed $values
* #param string $boolean
* #param bool $not
* #return \Illuminate\Database\Query\Builder|static
*/
public function whereIn($column, $values, $boolean = 'and', $not = false)
{
$type = $not ? 'NotIn' : 'In';
// If the value of the where in clause is actually a Closure, we will assume that
// the developer is using a full sub-select for this "in" statement, and will
// execute those Closures, then we can re-construct the entire sub-selects.
if ($values instanceof Closure)
{
return $this->whereInSub($column, $values, $boolean, $not);
}
$this->wheres[] = compact('type', 'column', 'values', 'boolean');
$this->bindings = array_merge($this->bindings, $values);
return $this;
}
Look that it has a third boolean param. Good luck.
You have a orWhereIn function in Laravel. It takes the same parameters as the whereIn function.
It's not in the documentation but you can find it in the Laravel API.
See the Laravel 8 orWhereIn documentation.
That should give you this:
$query-> orWhereIn('products.value', $f);
$query = DB::table('dms_stakeholder_permissions');
$query->select(DB::raw('group_concat(dms_stakeholder_permissions.fid) as fid'),'dms_stakeholder_permissions.rights');
$query->where('dms_stakeholder_permissions.stakeholder_id','4');
$query->orWhere(function($subquery) use ($stakeholderId){
$subquery->where('dms_stakeholder_permissions.stakeholder_id',$stakeholderId);
$subquery->whereIn('dms_stakeholder_permissions.rights',array('1','2','3'));
});
$result = $query->get();
return $result;
// OUTPUT #input $stakeholderId = 1
//select group_concat(dms_stakeholder_permissions.fid) as fid, dms_stakeholder_permissionss.rights from dms_stakeholder_permissions where dms_stakeholder_permissions.stakeholder_id = 4 or (dms_stakeholder_permissions.stakeholder_id = 1 and dms_stakeholder_permissions.rights in (1, 2, 3))
Yes, orWhereIn is a method that you can use.
I'm fairly sure it should give you the result you're looking for, however, if it doesn't you could simply use implode to create a string and then explode it (this is a guess at your array structure):
$values = implode(',', array_map(function($value)
{
return trim($value, ',');
}, $filters));
$query->whereIn('products.value', explode(',' $values));
Yes, orWhereIn where clause method exists in Laravel. Please see the below link of official Laravel Query Builder documentation for detailed information.
Documentation Link: https://laravel.com/docs/8.x/queries#additional-where-clauses
There are two ways to get the below output.
and (products.value in (Bomann, PHILIPS) OR products.value in (red,white))
Using orWhereIn
$query = Product::where('color', 'blue')
->whereIn('value', ['Bomann', 'PHILIPS'])
->orWhereIn('value', ['red', 'white'])
->get();
Output:
select * from `products` where `color` = 'blue' and `value` in (Bomann, PHILIPS) OR `value` in (red,white))
Using orWhere and whereIn
$query2 = Product::where('color', 'blue')
->whereIn('value', ['Bomann', 'PHILIPS'])
->orWhere(function ($query) {
$query->whereIn('value', ['Bomann', 'PHILIPS']);
})
->get();
Output:
select * from `products` where `color` = 'blue' and `value` in (Bomann, PHILIPS) OR (`value` in (red,white))
For example, if you have multiple whereIn OR whereIn conditions and you want to put brackets, do it like this:
$getrecord = DiamondMaster::where('is_delete','0')->where('user_id',Auth::user()->id);
if(!empty($request->stone_id))
{
$postdata = $request->stone_id;
$certi_id =trim($postdata,",");
$getrecord = $getrecord->whereIn('id',explode(",", $certi_id))
->orWhereIn('Certi_NO',explode(",", $certi_id));
}
$getrecord = $getrecord->get();

Categories