Laravel Query Builder: MySQL 'LIKE' inside a multiple where conditioned query - php

Im trying to do a query where i have multiple conditions (including %LIKE% operator) but can't figure how to do it in Laravel's array way with query builder.
$where = ['category' => $c->id, 'name' => $c->name];
$q = Store::where($where)->get();
That way it would return an array of objects with the equal of the name, not the similar matches. Is it possible to do a %LIKE% search in that way?

You should chain them like this:
DB::table('your-table-name')
->where('category','=','$c->id')
->where('name','=','$c->name')
->where('email', 'LIKE', '%test%')
->get();

Related

Laravel where :: model, how to add multi statement

So how i can add multi statement to query in ::where model.
Actually it lok like that:
certs::where('unique', '=', $newUnique )->get()
i need somethig like that:
certs::where('unique, num', '=', $newUnique,$key )->get()
so in sql look like that
Select * From certs Where unique = $newUnique AND num = $key
I need that to check if data need to be updated or inserted.
Just append another where clause
certs::where('unique', $newUnique)->where('num', $key)->get()
For example
App\User::where('first_name', 'John')->where('last_name', 'Doe')->toSql();
Would result in
"select * from `users` where `first_name` = ? and `last_name` = ?"
Hope this helps
It can become tricky if there will be OR instead of AND, so you should always prefer
for AND
Certs::where(function($query) use ([$newUnique, $key]){
$query->where('first_name', 'John')->where('last_name', 'Doe');
})->get();
for OR
Certs::where(function($query) use ([$newUnique, $key]){
$query->where('first_name', 'John')->orWhere('last_name', 'Doe');
})->get();
Laravel allows multi statements for "where" function of Model by passing array of conditions.
The below code can be used if you are applying "and" condition and "=" operation for each data.
$conditions = ['unique'=>$newUnique,'num'=>$key];
Certs::where($conditions)->get();
Else if you want to use different operations with "and" condition, use below code.
$conditions = [
['unique','=',$newUnique],['num','!=',$key]
];
Certs::where($conditions)->get();
Also, you can use below code for "and" and "or" conditions.
Certs::where(function($query) use ($newUnique, $key]){
$query->where('unique', $newUnique);
$query->orWhere('num', $key);
})->get();
Similarly, you can use orWhere(), whereColumn(), whereBetween() and other query builder functions.
You can do something like this:
certs::where(['unique'=>$newUnique, 'num' => $key])->get()

How can I build a condition based query in Laravel using eloquent

I was wondering how can I build a condition based query in Laravel using eloquent?
I've found how to do it with a raw query but that that's not what I want also the answer to this question isn't that dynamic at least not as dynamic as I want it to be.
What I try to achieve is to create a dynamic WHERE query based on certain conditions, for example if the field is filled or not.
If I use the following code,
$matchThese = [
'role' => 'user',
'place' => \Input::get('location')
];
$availableUsers = User::where($matchThese)->take($count)->orderByRaw("RAND()")->get();
The query will fail if I don't send a location as POST value. I don't want it to fail I want it to skip to the next WHERE clause in the query. So basically if there's no place given don't search for it.
Build up the query and include the ->where() clause depending on whether or not you have the location in your input:
$query = User::where('role', 'user');
$query = \Input::has('location') ? $query->where('location', \Input::get('location')) : $query;
$availableUsers = $query->take($count)->orderByRaw('RAND()')->get();
Just build the array with an if condition:
$matchThese = [
'role' => 'user',
];
if(\Input::has('location')){
$matchThese['place'] = \Input::get('location');
}
$availableUsers = User::where($matchThese)->take($count)->orderByRaw("RAND()")->get();
$query = DB::table('table_name');
if($something == "something"){
$query->where('something', 'something');
}
$some_variable= $query->where('published', 1)->get();
You can use something like this.

Different values when use DB::raw() in second param on where()

I have next query in Laravel Eloquent:
$buildings = Building::select('buildings.*')->join(
DB::raw('('.
(
IngameBuilding::select('buildings.building_id', 'buildings.level')
->join('buildings', 'buildings.id', '=', 'ingame_buildings.building_id')
->toSql()
).
') as `added_buildings`'), 'added_buildings.building_id', '=', 'buildings.building_id')
->where('buildings.level', '>', 'added_buildings.level')
->get();
This query returns all allowed rows from base, but one row more. When I added DB::raw() in where() return values is valid.
Good-working code:
$buildings = Building::select('buildings.*')->join(
DB::raw('('.
(
IngameBuilding::select('buildings.building_id', 'buildings.level')
->join('buildings', 'buildings.id', '=', 'ingame_buildings.building_id')
->toSql()
).
') as `added_buildings`'), 'added_buildings.building_id', '=', 'buildings.building_id')
->where('buildings.level', '>', DB::raw('`added_buildings`.`level`'))
->get();
Why first code workig, hmm.. Wrong?
I'm not a big fan of Laravel at all.
I've got only small experience with this framework but i'm almost sure that where function accepts only a 'constant' values to be checked against.
If you'll get an output of this query using toSQL method on the query object you will see that eloquent will convert it as something like:
(...) where buildings.level > 'added_buildings.level'
so the condition checks if the buildings.level (whatever the type is)
is greater than the given string and not the column value.
Using the DB::raw you're getting the proper sql as the eloquent won't parse/convert it.
You would need to use whereRaw method I suppose.
http://laravel.com/docs/4.2/queries#introduction

Use an array in Laravel update query

I would like to push an array in Where Clause of Laravel Update Query.
Here is the update query.
DB::table('users')->where('id', 1)->update(array('votes' => 1));
Is it possible to use the query like below ??
$array_of_ids;
DB::table('users')->where($array_of_ids)->update(array('votes' => 1));
Thanks
Simply use whereIn:
$array_of_ids;
DB::table('users')->whereIn('id', $array_of_ids)->update(array('votes' => 1));
Please read the documentation carefully. In this case, all kinds of where statements are documented here: Query Builder - Selects
Try this query:
DB::table('users')->whereIn('id', $array_of_ids)->update(['votes' => 1]);
Using Model:
User::whereIn('id', $array_of_ids)->update(['votes' => 1]);
using the query builder: The query builder can also update existing records using the update method. The update method, like the insert method, accepts an array of column and value pairs containing the columns to be updated. You may constrain the update query using where clauses:
DB::table('users')
->where('id', 1)
->update(['votes' => 1]);

How to use query builder with sum() column and groupBy

How would I use query builder in Laravel to generate the following SQL statement:
SELECT costType, sum(amountCost) AS amountCost
FROM `itemcosts`
WHERE itemid=2
GROUP BY costType
I have tried several things, but I can't get the sum() column to work with a rename.
My latest code:
$query = \DB::table('itemcosts');
$query->select(array('itemcosts.costType'));
$query->sum('itemcosts.amountCost');
$query->where('itemcosts.itemid', $id);
$query->groupBy('itemcosts.costType');
return $query->get();
Using groupBy and aggregate function (sum / count etc) doesn't make sense.
Query Builder's aggregates return single result, always.
That said, you want raw select for this:
return \DB::table('itemcosts')
->selectRaw('costType, sum(amountCost) as sum')
->where('itemid', $id)
->groupBy('costType')
->lists('sum', 'costType');
Using lists instead of get is more appropriate here, it will return array like this:
[
'costType1' => 'sumForCostType1',
'costType2' => 'sumForCostType2',
...
]
With get you would have:
[
stdObject => {
$costType => 'type1',
$sum => 'value1'
},
...
]

Categories