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
Related
in my laravel controller i'm trying to perform the following query for the user search.
$data = User::orderBy('id','DESC')
->where('email','LIKE','%'.$request->search."%")
->orwhere('first_name','LIKE','%'.$request->search."%")
->orwhere('last_name','LIKE','%'.$request->search."%")
->WHERE('role_id','=','3')
->paginate(12);
return view('admins.participants.results',compact('data'))
->with('i', ($request->input('page', 1) - 1) * 12 );
What I really want to perform is,
SELECT * FROM USERS WHERE role_id='3' AND email LIKE '%search_string%' OR first_name LIKE '%search_string%' OR last_name LIKE '%search_string%' ;
But the above laravel query outputs all the users without considering the `role_id=3
You can use where callback
$data = User::orderBy('id','DESC')
->where('role_id',3)
->where(function($query)use($request){
$query->where('email','LIKE','%'.$request->search."%");
$query->orwhere('first_name','LIKE','%'.$request->search."%");
$query->orwhere('last_name','LIKE','%'.$request->search."%");
})->paginate(12);
also you can change
'%'.$request->search."%"
to
"%{$request->search}%"
You need to pass OR clauses to a Closure to group them, otherwise the query doesn't really understand which clauses are optional and which are not.
$data = User::orderBy('id','DESC')
->where('role_id','=','3')
->where(function($query) use ($request) {
$query->where('email','LIKE','%'.$request->search."%")
->orwhere('first_name','LIKE','%'.$request->search."%")
->orwhere('last_name','LIKE','%'.$request->search."%");
})
->paginate(12);
Im new to this Framework, i dont know how to optimize it using db::raw count and aliases and display it to my blade.php using #foreach
im trying to optimize my code, my goals is to count pallet_conditions and store it to my aliases, i dont want to count it one by one like what i did on this code
this is my code not optimize:
//computing the total rapairable
$repairable_total = DB::table('liip_psrm_items')
->where('psrm_items_id', '=' , $psrm_maintenance->id)
->where('pallet_condition', '=', 1)
->count();
//REPAIRABLE
//computing the total good pallets
$good_total = DB::table('liip_psrm_items')
->where('psrm_items_id', '=' , $psrm_maintenance->id)
->where('pallet_condition', '=', 0)
->count();
//GOOD
this is the code, what i wanted to learn. just to minimize, and use aliases
$result = DB::table('liip_psrm_items')
->select(DB::raw('COUNT(liip_psrm_items.pallet_condition = 0 ) AS condition_1',
'COUNT(liip_psrm_items.pallet_condition = 1 ) AS condition_2'))
->where('psrm_items_id', '=' , $psrm_maintenance->id)
->get();
You can't use single query for two different results, which has totally opposite conditions.
Case 1. You are trying to count the items where pallet_condition = 1;
Case 2. You are trying to count the items where pallet_condition = 0;
Now you want to merge these two cases into single query, which is impossible...
So, For these two cases, you have to use either separate queries ( what you did already )
or you can use single query to grab all the items and then use PHP to separate them.
Like:
$total_items = DB::table('liip_psrm_items')
->where('psrm_items_id', '=' , $psrm_maintenance->id)
->get();
$repairable_count = count(array_filter($total_items, function($item){
return (bool)$item->pallet_condition;
}));
$good_count = count(array_filter($total_items, function($item){
return !(bool)$item->pallet_condition; //just inverse of the above condition
}));
i hope this might help.
To count at multiple condition I used this approach
$lastMonthInvoices = Invoice::select(DB::raw("(COUNT(*)) as count"), DB::raw('SUM(total) as total'),'status')
->whereDate('created_at', '>', Carbon::now()->subMonth())
->groupBy('status')
->get();
i got the result with groupBy Status and in each group total number of records as count & also their sum as total
these two snaps are of one query result
You can, first group by, then get count
Like :
DB::table('liip_psrm_items')
->groupBy('pallet_condition')
->select('pallet_condition', DB::raw('count(*) as total'))
->get();
Try to pass a closure like so:
$results = DB::table('liip_psrm_items')
->where('psrm_items_id', '=' , $psrm_maintenance->id)
->where(function($query){
$query->where('pallet_condition', 1)
->orWhere('pallet_condition', 0);
})->count();
I have the following query in my controller.
$items = Item::with(['subitems' => function($query) {
$query->where('language_id', '=', 1);
}])->get();
This is correctly getting me all items including subitems that have a language id of 1.
There are two things I would like to do with this though
Firstly, I need to return all subitems that have a distinct 'ref_id' value.
Secondly, I would like to give preference to the language id 1 but if none exist, use any language id.
So for example, I know this code won't work, but the sort of thing I am looking for is:
$items = Item::with(['subitems' => function($query) {
$subItems = $query->where('language_id', '=', 1)
->where('ref_id', 'is', 'distinct');
if($subItems->count() <= 0) {
$subItems = $query->where('ref_id', 'is', 'distinct');
}
}])->get();
Is this possible or is it a bit too complicated for Query Builder? Even if one of the two requests was possible, that would be great.
Try this:
$items = Item::with(['subitems' => function($query) {
$join = Subitem::select('ref_id', DB::raw('MIN(language_id) language_id'))
->groupBy('ref_id');
$sql = '(' . $join->toSql() . ') subitems_distinct';
$query->join(DB::raw($sql), function($join) {
$join->on('subitems.ref_id', 'subitems_distinct.ref_id')
->on('subitems.language_id', 'subitems_distinct.language_id');
});
}])->get();
We can use the fact that your preferred language_id is the lowest value and select the minimum.
I am trying to loop in an array but when it comes to the query it gets only the first element, so a little help would be very important.
$data = Offers::whereIn('id_business', $business_id_array)
->where([
'visible' => 'yes',
'delete' => 'no'
])
->where('end_date', '>=', date('Y-m-d h:m:i'))
->orderBy('id', 'desc')
->get();
$data=array($data);
foreach($data as $key => $item) {
$offers = DB::select('the data i need to get WHERE o.`id` = ' . $item[$key]['id']);
}
and this is my problem in here, It gets only the id of the first element
o.`id` = ' . $item[$key]['id']
because you have return the view in side the foreach loop, so it only loop through the first item and return. What you can do with this case is
$data = Offers::whereIn('id_business', $business_id_array)...->get()->toArray();
$offers = array_map(function($item){
$offer = DB::select('the data i need to get WHERE o.`id` = ?', [$item->id]);
return $offer;
},$data);
return view(....,['offers' =>$offers]);
First, you do not need to cast the $data to an array - it will get returned as a collection, which you can iterate through like an array. So you'll be able to use something like this
$offers = Offers::whereIn('id_business', $business_id_array)...->get();
foreach ($offers as $offer) {
$moreData = DB::select('the data i need to get WHERE o.`id` = ?', [$offer->id]);
}
This looks like you are using the id from one table, to get the associated data from another table.
Should there not be a relationship in place, between the two tables?
The answer from #Chris G looks correct, maybe dd($offers) to be certain what is in there.
Mick
I have the problems using the array input as a value in WHERE clause.
But don't want to use more than once in WHERE clause code.
In my case, this is what I want :
$cond = array('job_id' => $job_id_var, 'job_name' => $job_name_var);
//WHERE clause
$this->where($cond); //only using once WHERE clause code like this, array as input
//which means
WHERE job_id = '$job_id_var' AND job_name = '$job_name_var'
is it possible to do that in codeigniter?
Yes, the ->where() method can support that.
Since you do not want to cascade it:
$this->db->where('job_id', $job_id_var);
$this->db->where('job_name', $job_name_var);
->where() can handle array input as well:
$cond = array('job_id'=>$job_id_var, 'job_name'=>$job_name_var);
$this->db->where($cond); // here, only used once.
$query = $this->db->get('hello_table');
$result = $query->result_array();
return $result;