Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have this query
$something = Something::where('height, '>=', $request->heightMin)
->where('height, '<=', $request->heightMax)
->get();
It works but what if I want to use field age. This filed isn't require so I may have value (int) or null. So if i had value "null", I want this field to be ignored. How can I do that?
You can use when to only apply the query when the value exists in the request.
From the docs:
Sometimes you may want clauses to apply to a query only when something
else is true. For instance you may only want to apply a where
statement if a given input value is present on the incoming request.
You may accomplish this using the when method:
$role = $request->input('role');
$users = DB::table('users')
->when($role, function ($query, $role) {
return $query->where('role_id', $role);
})
->get();
The when method only executes the given Closure when the first
parameter is true. If the first parameter is false, the Closure will
not be executed.
Something like this:
$something = Something::where('height', '>=', $request->heightMin)
->where('height', '<=', $request->heightMax)
->when($request->age, function ($query, $age) {
// your query here
$query->where('age', $age);
})
->get();
Use "Between":
MySQL Raw Query WHERE Statement Example:
WHERE height BETWEEN :heightMin AND :heightMax
Looks like laravel, if it is take a look at:
https://laravel.com/docs/8.x/queries#additional-where-clauses
$something = Something::whereBetween('height', [1, 100])
->get();
However, if its not laravel, go in your IDE .. if you type just "where" if you find something like whereBetween in your autocompletion
If there is a problem with null values in the database you can do a (and)Where height IS NOT NULL .. You can also split your query like
$something = Something::where('height, '>=', $request->heightMin);
if($request->heightMax !== null){
something = something->where('height, '<=', $request->heightMax)
}
something->get();
if you want to remove age field and order you have to add where to your query like this:
$something = Something::where('height, '>=', $request->heightMin)
->where('height, '<=', $request->heightMax)
->where('age, '!=', null)
->get();
but if you want to have empty age field at the end of your query result and order just others that have value you should better do something like this:
$something = Something::where('height, '>=', $request->heightMin)
->where('height, '<=', $request->heightMax)
->orderBy(Illuminate\Support\Facades\DB::raw('ISNULL(`age`), `age`'), 'ASC')
->get();
Related
How do I add the where clause only on the count()? Using ->where('point',1) will affect the end result of the whole table and that's not what I want. I want to calculate the count of points where it's grouped by the child_id and the point column equals 1.
$chore_contents = DB::table('chores_content')
->join('children', 'children.id', '=', 'chores_content.child_id')
->select('chores_content.id as content_id','chores_content.*', 'children.*', DB::raw("COUNT(point) as points"))
->where('chores_content.user_id', Auth::id())
->where('chores_content.chores_id', $id)
->groupBy('chores_content.child_id')
->get();
return $chore_contents;
Use havingRaw to implement this:
$chore_contents = DB::table('chores_content')
->join('children', 'children.id', '=', 'chores_content.child_id')
->select('chores_content.id as content_id','chores_content.*', 'children.*', DB::raw("COUNT(point) as points"))
->where('chores_content.user_id', Auth::id())
->where('chores_content.chores_id', $id)
->groupBy('chores_content.child_id')
->havingRaw('COUNT(point) =1')
->get();
return $chore_contents;
I hope it helps.
This question lacks some clarity, so this is simply an educated guess at this point.
First to clarify that when you do this: count(point) you already exclude rows where point is null. You should not be count(point) if you want to include rows where point is null.
Given your comments you seem to be contradicting your statement that you only want rows where point=1. It now appears you want rows where point = 1 or point is null.
To do this with eloquent, you would need to have parens around the (point=1 OR point IS NULL) which you can do by passing an anonymous function:
$chore_contents = DB::table('chores_content')
->join('children', 'children.id', '=', 'chores_content.child_id')
->select('chores_content.id as content_id','chores_content.*', 'children.*', DB::raw("COUNT(*) as points"))
->where('chores_content.user_id', Auth::id())
->where('chores_content.chores_id', $id)
->where(function ($chore_contents) {
$chore_contents->where('point',1)
->orWhereNull('point');
})
->groupBy('chores_content.child_id')
->havingRaw('COUNT(point) =1')
->get();
return $chore_contents;
I have one table named as Package. Currently, I want to filter the table actually. Let say the user insert values into variable, for example, from = 2/3/2020 and to = 10/3/2020. Then it will be calculated inside my coding and get the duration of days, resulting noOfdays = 8 days. So, from the duration, it will determined, which packages it belongs within the duration of 8 days.
calculation of days :
$today = Carbon::now();
$dt1 = Carbon::createFromFormat('d/m/Y',$departure);
$dt2 = Carbon::createFromFormat('d/m/Y',$arrival);
$noOfDays = $dt1->diffInDays($dt2);
The calculation have no error, which when dd($noOfDays), it will result = 8 days.
SQL statement :
$packages = Package::where([
['id', '=', $plan],
['from', '<=', $noOfDays, 'AND', 'to', '>=', $noOfDays],
])
->get();
Package Table :
The error part is, when I filtering, it will get Package 1 and package 2. It supposed to get only the package 2. I think it have something wrong somewhere around the SQL statement. Anyone whoever in this situation before? because logically I think, the SQL part is true already. But it why it filter and get the package 1?
You have to separate your two where clause to get what you wanted like this.
$packages = Package::where([
['id', '=', $plan],
['from', '<=', $noOfDays],
['to', '>=', $noOfDays]
])
->get();
To be more readable, its good if your code goes like this
$packages = Package::where('id', $plan)
->where('from', '<=', $noOfDays)
->where('to', '>=', $noOfDays)
->get();
Change your second where statement. Where clause is always using an ADN unlelss you use orWhere or nest it in a function.
['id', '=', $plan],
['from', '<=', $noOfDays],
['to', '>=', $noOfDays]
The 4th parameter, that you are passing as an AND is not used like you are expecting it to work.
Which results to package1 to be included in your output.
I'm trying filtered a collection, but the code in the last row does not work. In this row the $property->county_id is an integer, the params.county_id is an array. I would like know the array contains the integer.
I think the code is wrong, because the key (maybe) must be the params.county_id. How I can do this?
Thanks the answers.
$buyerSearches = collect($items);
$result = $buyerSearches
->where('params.type', '=', $property->type)
->where('params.sale_type', '=', $property->sale_type)
->whereIn('params.contract_type', ['all', $property->contract_type])
->where('params.min_price', '<=', $property->price)
->where('params.max_price', '>=', $property->price)
->whereIn($property->county_id, 'params.county_id');
Be sure that the second argument in the whereIn is an array or create that array before the $result query and use it next.
I solved, it works :)
$result = $buyerSearches
->where('params.type', '=', $property->type)
->where('params.sale_type', '=', $property->sale_type)
->whereIn('params.contract_type', ['all', $property->contract_type])
->where('params.min_price', '<=', $property->price)
->where('params.max_price', '>=', $property->price)
->filter(function($buyerSearch) use ($property) {
return in_array($property->county_id, $buyerSearch['params']['county_id']);
});
Try this code instead :
->whereIn('county_id', 'params.county_id');
I want to get the template from user_webhook table in my database.In WHERE condition i am checking user_id,app_id and if either notify_admin or notify_customer value is 1 in user_webhook table.I am using query..
$templates= $this->where('notify_admin',1)
->orwhere('notify_customer',1)
->where('user_webhooks.user_id',$user_id)
->where('user_webhooks.app_id',$app_id)
->select( 'webhooks.id as webhook_id','webhooks.app_id','webhooks.topic','webhooks.type','webhooks.action',
'webhooks.sms_template','user_webhooks.id','user_webhooks.notify_admin',
'user_webhooks.notify_customer','user_webhooks.user_id','user_webhooks.sms_template_status',
'user_webhooks.sms_template as sms'
)
->join ('webhooks',function($join){
$join>on('webhooks.id','=','user_webhooks.webhook_id');
})
->get()
->toArray();
when i get query using DB::getQueryLog(), I found the query seems Like
select `telhok_webhooks`.`id` as `webhook_id`, `telhok_webhooks`.`app_id`,
`telhok_webhooks`.`topic`, `telhok_webhooks`.`type`, `telhok_webhooks`.`action`,
`telhok_webhooks`.`sms_template`, `telhok_user_webhooks`.`id`,
`telhok_user_webhooks`.`notify_admin`, `telhok_user_webhooks`.`notify_customer`,
`telhok_user_webhooks`.`user_id`, `telhok_user_webhooks`.`sms_template_status`,
`telhok_user_webhooks`.`sms_template` as `sms` from `telhok_user_webhooks`
inner join
`telhok_webhooks` on `telhok_webhooks`.`id` = `telhok_user_webhooks`.`webhook_id`
where `notify_admin` = ? or `notify_customer` = ? and `telhok_user_webhooks`.`user_id`
= ? and `telhok_user_webhooks`.`app_id` = ?
The result of query giving result of all app_id and user_id.
So Please tell me use of OR in where condition.
Thanks in advance.
You may chain where constraints together as well as add or clauses to the query. The orWhere method accepts the same arguments as the where method:
$users = DB::table('users')
->where('votes', '>', 100)
->orWhere('name', 'John')
->get();
Advanced usage:
Usere::where('id', 46)
->where('id', 2)
->where(function($q) {
$q->where('Cab', 2)
->orWhere('Cab', 4);
})
->get();
The whereIn method verifies that a given column's value is contained within the given array:
$users = DB::table('users')
->whereIn('id', [1, 2, 3])
->get();
More: https://laravel.com/docs/5.5/queries
Change
->where('notify_admin',1)
->orwhere('notify_customer',1)
to
->where(function($q){
$q->where('notify_admin',1)
->orWhere('notify_customer',1);
})
Without this, the orWhere will compare to all other wheres in your query instead of just comparing those two columns
How to make a whereclause that is based on an existing field in the database, and not on an input parameter?
$query = DB::table('events')
->join('events_dates', function($join) use ($data){
$join->on('events.id', '=', 'events_dates.event_id');
$join->where('events_dates.start_date', "<=", $data['date_end']);
$join->where('events_dates.end_date', '>=', $data['date_start']);
});
This works well because the where clause is based on an input parameter.
What I need is a Where clause that is based on a field that is already in the database:
Something like this:
$query = DB::table('events')
->join('events_dates', function($join) use ($data){
$join->on('events.id', '=', 'events_dates.event_id');
//If db field of record: recurrent == 0 then
$join->where('events_dates.start_date', "<=", $data['date_end']);
$join->where('events_dates.end_date', '>=', $data['date_start']);
/* If db field of record: "recurrent" == "1" then
$join->where //another query
*/
});
Is this achievable with the laravel ORM, or should I write a native SQL query?
Haven't found a suitable answer in the docs or in existing posts.
You need to use...
where('column1', '=', DB::raw('column2'));
...to use the field value instead of the string "column2".
In this answer I further explained why.