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

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

Related

Wildcard-like syntax in an eloquent Where clause to search between two strings

I saw the answer provided in this question Wildcard-like syntax in an eloquent Where clause? now I want to know if is there a way to search between two strings?.
basicasicaly in my code I want to show requests that have a status of new or scheduled.
$requests = DB::table('requests')
->select('requestDate','requestTime','status','requestID')
->where('requestorID', '=',$userID)
->where('status', 'LIKE','%New%')
->get();
you can use whereIn ,The whereIn method verifies that a given column's value is contained within the given array:
$requests = DB::table('requests')
->select('requestDate','requestTime','status','requestID')
->where('requestorID', '=',$userID)
->whereIn('status', ['new','scheduled'])
->get();
You can use:
->where('status', 'new')
->orWhere('status', 'scheduled')
you can simply use a where with an orWhere:
$requests = DB::table('requests')
->select('requestDate','requestTime','status','requestID')
->where('requestorID', '=',$userID)
->where(function($q) {
$q->where('status', 'LIKE','%New%');
$q->orWhere('status', 'LIKE','%Scheduled%');
})->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();

Using day, Month or Year as MYSQL query filter in Laravel

In my code, i am querying a database by accepting month and year input from user.
I have tried writing it the normal PHP way and other ways i can find online but none seems to be working. here is the code i am using currently
$salesmonth = $request->input('mn');
$salesyear = $request->input('yr');
$id = Auth::user()->id;
$comm = \DB::table('bakerysales')
->where([
['customer_id', '=', $id], [MONTH('sales_date'), '=', $salesmonth], [YEAR('sales_date
'), '=', $salesyear]
])
->get();
return view::make('showCommission')->with('comm', $comm);
I expect the query to return data from rows that match user selected month and year
Laravel comes with a few different where clauses for dealing with dates e.g.
whereDate / whereMonth / whereDay / whereYear.
This means that your controller method can look something like:
$comm = \DB::table('bakerysales')
->where('customer_id', auth()->id())
->whereMonth('sales_date', $request->input('mn'))
->whereYear('sales_date', $request->input('yr'))
->get();
return view('showCommission', compact('comm'));

Eloquent ORM - where(), how to include both parameters as table fields

$data = Booking::join('user', 'booking.user_id', '=', 'user.id')
->join('tickets', 'trail_booking.tkt_id', '=', 'tickets.id')
->where('trail_booking.user_id','=','tickets.user_id')
->paginate();
I am unable to get any result using the above query as the 'where' condition evaluates 'tbl_tickets.user_id'to the value instead of table field.
Should I use whereRaw? Or is there any method to correct this?
Because the third parameter is expected to be a value, it will be escaped and quoted, so you should use whereRaw instead:
$data = Booking::join('user', 'booking.user_id', '=', 'user.id')
->join('tickets', 'trail_booking.tkt_id', '=', 'tickets.id')
->whereRaw('trail_booking.user_id = tickets.user_id')
->paginate();
You could alternatively pass the value with DB::raw so it's not escaped:
->where('trail_booking.user_id', DB::raw('tickets.user_id'))
But it's cleaner and more readable with whereRaw in my opinion and it does the same thing.

Convert raw SQL to use Eloquent Query Builder

How can I convert the following complex SQL query to use the Eloquent query builder? I want to use methods such as join() and where(), get() etc.
The below query returns a list of locations along with counts for vouchers that have been redeemed.
select
a.location_name,
'' as dates,
a.places,
sum(netvalue155),
sum(netvalue135) from
(
select
l.id,
l.location_name,
b.places,
case when v.net_value = 155 then 1 else 0 end as netvalue155,
case when v.net_value = 135 then 1 else 0 end as netvalue135
from locations l
left join bookings b on l.id = b.location_id
left join vouchers v on b.voucher_code = v.voucher_code
) a
right join locations l on l.id = a.id
group by a.location_name
EDIT
I am trying the below code, which throws the error SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sub.id' in on clause
$subQuery = DB::table('locations')
->select(
'locations.id',
'locations.location_name',
DB::raw('"'.$request->get('dates').'" as dates'),
DB::raw('sum(bookings.id) as number'),
DB::raw('round(sum(bookings.final_price/1.2), 2) as paidbycard'),
DB::raw('case when bookings.voucher_value = 155 then round(sum(bookings.voucher_value/1.2), 2) else 0.00 end as voucher155'),
DB::raw('case when bookings.voucher_value = 135 then round(sum(bookings.voucher_value/1.2), 2) else 0.00 end as voucher135'),
DB::raw('case when bookings.transfer_fee = 10 then round(sum(bookings.transfer_fee/1.2), 2) else 0.00 end as transfer_fee'))
->leftJoin('bookings', 'locations.id', '=', 'bookings.location_id');
$meatBookQuery = DB::table('orders')->select(DB::raw('sum(orders_items.price) as total'))
->join('orders_items', 'orders.id', '=', 'orders_items.order_id')
->where('orders_items.item_name', 'The Meat Book');
$booking = DB::table(DB::raw("({$subQuery->toSql()}) as sub, ({$meatBookQuery->toSql()}) as meatBook"))
->mergeBindings($subQuery)
->mergeBindings($meatBookQuery)
->select('sub.location_name', 'sub.dates', 'sub.number', 'sub.paidbycard', 'sub.voucher155', 'sub.voucher135', 'sub.transfer_fee', DB::raw('round(sum(sub.voucher155 + sub.voucher135 + sub.transfer_fee + sub.paidbycard), 2) as total'), 'meatBook.total')
->leftJoin('locations', 'locations.id', '=', 'sub.id')
->leftJoin('bookings', 'bookings.location_id', '=', 'sub.id')
->groupBy('sub.location_name');
First of all
I often see people asking for how to rebuild a complex SQL query in Laravels Query Builder. But not every operation which is possible in SQL or MySQL is implemented as a function in Laravels Query Builder. This means you can't rebuild every SQL query in Query Builder without using raw SQL.
What does this mean for your SQL query?
Some things like sub queries (the from (select ...) part) and the case when ... part is not implemented in Query Builder. At least therefore you will have to use the raw expression with the DB::raw() function. I'm not sure about the sum() if this is already possible but you will surely find that in the docs.
Other things like joins are implemented as a function:
$users = DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.id', 'contacts.phone', 'orders.price')
->get();
see Laravel Documentation: Queries - Joins
And you can even mix up Query Builder functions with raw expressions:
$users = DB::table('users')
->select(DB::raw('count(*) as user_count, status'))
->where('status', '<>', 1)
->groupBy('status')
->get();
see Laravel Documentation: Queries - Raw Expression
Example for a sub query:
$subQuery = DB::table('locations')
->leftJoin('bookings', 'locations.id', '=', 'bookings.location_id')
->leftJoin('vouchers', 'bookings.voucher_code', '=', 'vouchers.voucher_code')
->select('locations.id', 'locations.location_name', 'bookings.places');
$query = DB::table(DB::raw("({$subQuery->toSql()} as sub"))
->mergeBindings($subQuery)
->select(...)
->rightJoin(...)
->groupBy('sub.location_name')
->get();
So you can rebuild some parts of the query in Query Builder and use raw expressions wherever you need to.
To debug a query while you build it Laravels query logging function can be very helpful.

Resources