Pagination shows error when use having in query builder - laravel

I have a query like the following, and it works as expected. I used here the havingRaw option to filter the result.
$customers = Customer::select(DB::raw("`name`, `mobile`, `branch`, count(*) as total_orders"))
->groupBy('mobile')
->havingRaw('total_orders > 12')
->orderBy('total_orders', 'desc')
->get();
As the total number of returned row will vary, i need to show it as paginated. So i changed the query like below. Then it shows error that the total_orders column not found.
$customers = Customer::select(DB::raw("`name`, `mobile`, `branch`, count(*) as total_orders"))
->groupBy('mobile')
->havingRaw('total_orders > 12')
->orderBy('total_orders', 'desc')
->paginate();
I found some workarounds for the previous versions of Laravel. I am using Laravel 5.6 for my project, is there any solution for this?

Try this..
$customers = Customer::select(DB::raw("`name`, `mobile`, `branch`, count(*) as
total_orders"))
->groupBy('mobile')
->having('total_orders','>', 12)
->orderBy('total_orders', 'desc')->get();

Related

How to get created column using SelectRaw and use it inside whereBetween

I've got a laravel eloquent query which uses selectRaw and whereBetween:
$offset = '+8:00';
$d["records"] = data_entries::select("*")
->selectRaw("CONVERT_TZ (testTime, '+0:00', '{$offset}') as convertedTime")
->whereBetween("testTime", $filters['duration'])
->where('data_entries.patientID_FK', '=', $patient['patientID'])
->leftjoin('additional_notes', 'ID', '=', 'additional_notes.entryID_FK')
->get();
So this query works and I can get convertedTime data. But I want to use convertedTime instead of testTime in whereBetween like this:
$d["records"] = data_entries::select("*")
->selectRaw("CONVERT_TZ (testTime, '+0:00', '{$offset}') as convertedTime")
->whereBetween("convertedTime", $filters['duration'])
->where('data_entries.patientID_FK', '=', $patient['patientID'])
->leftjoin('additional_notes', 'ID', '=', 'additional_notes.entryID_FK')
->get();
but I got error saying unknown column 'convertedTime'. Is there a way to get the date that was converted based on timezone inside the whereBetween?
You cannot refer to an alias defined in the select clause in the where clause at the same level of the query. But it just so happens that MySQL has overloaded the HAVING operator such that it can be used in place of WHERE, with the added feature that it can also refer to aliases. Consider the following version:
$d["records"] = data_entries::select("*")
->selectRaw("CONVERT_TZ (testTime, '+0:00', '{$offset}') AS convertedTime")
->where('data_entries.patientID_FK', '=', $patient['patientID'])
->leftjoin('additional_notes', 'ID', '=', 'additional_notes.entryID_FK')
->havingRaw("convertedTime >= ? AND convertedTime <= ?", $filters['duration'])
->get();

db::raw adding is null in query

I am trying to use laravel query builder like:-
$users = DB::table('baid_collection')
->select(DB::raw('sum(total) as total_collect,collection_limit_c'))
->join('users_cstm', 'baid_collections.assigned_user_id', '=', 'users_cstm.id_c')
->where(DB::raw("assigned_user_id = '$userId' and DATE(date_entered)=CURDATE()"))
->groupBy('assigned_user_id')
->get();
This query should be like
select sum(total) as total_collect,collection_limit_c from `baid_collections` inner join `users_cstm` on `baid_collections`.`assigned_user_id` = `users_cstm`.`id_c` where assigned_user_id = '15426608-3ea5-f299-7a80-601bd06be2d9' and DATE(date_entered)=CURDATE() group by `assigned_user_id`
But last run query showing me
select sum(total) as total_collect,collection_limit_c from `baid_collection` inner join `users_cstm` on `baid_collections`.`assigned_user_id` = `users_cstm`.`id_c` where assigned_user_id = '15426608-3ea5-f299-7a80-601bd06be2d9' and DATE(date_entered)=CURDATE() is null group by `assigned_user_id`
In query is null giving problem i dont want is null in query
Use whereRaw instead of where like
$users = DB::table('baid_collections')
->select(DB::raw('sum(total) as total_collect,collection_limit_c'))
->join('users_cstm', 'baid_collections.assigned_user_id', '=', 'users_cstm.id_c')
->whereRaw("assigned_user_id = '{$userId}' and DATE(date_entered)=CURDATE()")
->groupBy('assigned_user_id')
->get();
It's creating a problem due to where needs atleast two parameters and you are just passing one parameter
Check this if it helps, write whereDate instead of add date in raw query.
if you are not using Carbon, you can also use php date("Y-m-d"), method to get date
DB::table('baid_collection')
->select(DB::raw('sum(total) as total_collect,collection_limit_c'))
->join('users_cstm', 'baid_collections.assigned_user_id', '=', 'users_cstm.id_c')
->where(DB::raw("assigned_user_id = '$userId'"))
->whereDate("date_entered", "=", Carbon::now()->toDateString())
->groupBy('assigned_user_id')->get();
You can try this
$users = DB::table('baid_collection')
->select(DB::raw('sum(total) as total_collect,collection_limit_c'))
->join('users_cstm', 'baid_collections.assigned_user_id', '=', 'users_cstm.id_c')
->where(DB::raw("assigned_user_id = '$userId' and DATE(date_entered) = '".date('Y-m-d')."'"))
->groupBy('assigned_user_id')
->get();

Laravel query builder strange result with join

I have a query
$orders = DB::table('orders')->where('user_id', $user->id)->get();
And this is what I have in view:
#foreach ($orders as $order)
{{ $order->id }}
#endforeach
It prints out 1 2 3, because the table has these three IDs.
But if I try to join, I get a rather unpredicted result.
$orders = DB::table('orders')->where('user_id', $user->id)->
leftJoin('status', 'orders.status_id', '=', 'status.id')
->get();
It gives 2 1 1. Result is the same with rightJoin() and join().
I thought this command would append row from status table to every corresponding row of orders table. Join on orders.status_id = status.id.
Can I get an intended result?
I have tried ->select('orders.*') but it did not change the result.
But still, I needed to alias everything out, as suggested in the comments here. So here is my final query.
$orders = User::find($user->id)->orders()->
select('orders.id as order_id', 'status.id as status_id',
'status.label as label', 'orders.ordered_at as ordered_at')
->leftJoin('status', 'orders.status_id', '=', 'status.id')
->get();
Probably this could be done in more pretty way, but this works.
Thank you who commented the post.
UPD: Now, I have fixed relations between my models and I can do this much simpler. As described here Laravel Many-to-one relationship
$orders = Order::with('status')->where('user_id', '=', $user->id)->get();

Order by is not working?

I have a problem with order by articles by priority. Where is working. Any suggestion?
$articles = Articles::whereHas('priority',function($query){
$query->orderBy('order','asc');
// $query->where('order','=',1);
})->limit(7)->get();
You have to use join to fetch the articles by the order of related table column as:
Articles::join('priority', 'articles.id', '=', 'priorities.article_id')
->orderBy('priorities.order','asc')
->select('articles.*')
->limit(7)
->get();
You can do the following:
$quotes=Articles::orderBy('priority', 'desc')->limit(7)->get();
Try this code
$articles = Articles::orderBy('order','desc')->limit(7)->get();
and if you want to add a condition you can use somthing like this:
$articles = Articles::join('priorities','articles.id','=','priorities.articale_id')->where('priority',1)->orderBy('order','desc')->limit(7)->get();

Laravel 5.3 “group by count” query issues

Please I am trying to run a query that looks like this in raw sql
SELECT `qnty`, COUNT(*) FROM cartlist GROUP BY `pro_id`,`cart_id`,`price`
in laravel.
I have tried this
$count = DB::table('cartlist')
->select(DB::raw('count(*) as qnty'))
->where('pro_id', '$tt->pro_id')
->where('cart_id', '$cart_id')
->groupBy('pro_id','price')
->get();
But it gives the following error
Object of class Illuminate\Support\Collection could not be converted to int
$count = DB::table('cartlist') ->select(DB::raw('count(*) as qnty'))
->where('pro_id', '$tt->pro_id')
->where('cart_id', '$cart_id')
->groupBy('pro_id','price','cart_id') ->get();

Resources