Want to get result between time range in Laravel - mysql

I have some records, i want to get records from them where item is not between given time range, here is my code that i already tried but no success
$other_hour_trade = DB::table('finaltrade')
->join('exchanges', 'finaltrade.exchange_id', '=', 'exchanges.id')
->select('finaltrade.*')
->where('finaltrade.user_id', $user_id)
->whereNotBetween('finaltrade.created_at', [DB::raw('exchanges.start_time'), DB::raw("ADDTIME(exchanges.start_time, '01:00:00')")])
->whereNotBetween('finaltrade.created_at', [DB::raw('exchanges.close_time'), DB::raw("SUBTIME(exchanges.close_time, '01:00:00')")])
->get();
'finaltrade.created_at' is a datetime field and
'exchanges.start_time' and 'exchanges.close_time' is a only time field
I have join two tables to get results

I don't know how to make this work directly using whereNotBetween, but since you're already trying to resort to some raw SQL in your current code, why not just use whereRaw instead:
$other_hour_trade = DB::table('finaltrade')
->join('exchanges', 'finaltrade.exchange_id', '=', 'exchanges.id')
->select('finaltrade.*')
->where('finaltrade.user_id', $user_id)
->whereRaw("finaltrade.created_at NOT BETWEEN exchanges.start_time AND ADDTIME(exchanges.start_time, '01:00:00')")
->whereRaw("finaltrade.created_at NOT BETWEEN exchanges.close_time AND SUBTIME(exchanges.close_time, '01:00:00')")
->get();

Related

The date returned is todays date instead of what is in the database with Laravel

To start, I have seen this question/answer but it isn't what I'm looking for.
The problem is, I need to be able to return a single result per match of orders.id + order_status_updates.id. When I get a single result the date gives the current date, but change nothing but the query, if I pull in all the results matching what I need but not the latest one I get the correct date/time from the database.
return Order::where('orders.user_id', auth()->id())
->join('order_statuses', 'order_statuses.id', 'orders.order_status_id')
->join('products', 'products.id', 'orders.product_id')
->join('brands', 'brands.id', 'products.brand_id')
->leftJoin('customers', 'orders.customer_id', '=', 'customers.id')
->leftJoin('b2b_businesses', 'b2b_businesses.id', 'orders.b2b_business_id')
->leftJoin('order_status_updates', function($join)
{
$join->select('max(order_status_updates.id) as osid', 'order_status_updates.updated_at');
$join->on('order_status_updates.order_id', '=', 'orders.id');
$join->on('order_status_updates.order_status_id','=', 'orders.order_status_id')
->where('order_status_updates.id', '=', 'osid');
});
Column::callback(['order_statuses.name',
'order_status_updates.updated_at'], function ($orderStatusName,
$orderStatusUpdate) {
$date = new Carbon($orderStatusUpdate);
return '<p>'.$orderStatusName. '</p><p>' . $date->month .'/'. $date->day .'/'. $date->year . '</p>';
})
->label('Status/Date')
->searchable()
->filterable(),
edit: to clarify, all I need to do is take out ->where('order_status_updates.id', '=', 'osid'); and I get the correct time stamp but then lose the return of a single row per match needed.

Rewrite MYSQL query using Laravel query builder

I'm trying to rewrite MYSQL query using Laravel query builder
So this is the query
DB::select("SELECT * FROM accomodation WHERE id NOT IN
(SELECT accomodation_id FROM bookings
WHERE (`checkin` <= '$request->in' AND `checkout` >= '$request->out'));");
And this is what I've done so far
Accommodation::whereNotIN('id', function($q)
{
$q->select('accomodation_id')
->from('bookings')
->where('checkin', '<=', '$request->out')
->where ('checkout', '>=', '$request->in');
})
->get();
The problem is the first query is giving me expected results but the second one isn't
Can someone point out what I'm doing wrong?
I think you type it wrong. Look at the $request->in and $request->out. You may want to flip it. and why you use '$request->in' instead of $request->in. It will parse as string instead of the value
You don't have use. For example php Accommodation::whereNotIN('id', function($q) use ($request) and you need to flip condition with request ;)

how to access the last record of a table of db and to the fields of the last record in laravel

I want to access a specific field of the db keeping in mind that I want to consult the last record of the database. I do this in laravel, for the moment I have the following:
$buscar=DB::table('ciclo') //In this way I look for the last record
->select(DB::raw('max(idCiclo) as idCiclo'))
->get();
then he tried to make a query in order to find the id of the last I record he searched before
$ultimo= DB::table('ciclo')
->select('idCiclo', 'fechaFinal')
->where('idCiclo', '=', $buscar)
->first();
When executing it tells me the following error
Object of class stdClass could not be converted to string
what's going on? I'd appreciate your help...
Object of class stdClass could not be converted to string
it is because $buscar is object of stdClass which has idCiclo attribute. (It is possible $buscar has null when in db no records)
$ultimo= DB::table('ciclo')
->select('idCiclo', 'fechaFinal')
->where('idCiclo', '=', $buscar->idCiclo)
->first();
You can do that more short ways
$maxIdCiclo = DB::table('ciclo')->max('idCiclo'); // return max idCiclo or null
$ultimo= DB::table('ciclo')
->select('idCiclo', 'fechaFinal')
->where('idCiclo', '=', $maxIdCiclo)
->first();
You can even try this
$ultimo= DB::table('ciclo')
->select('idCiclo', 'fechaFinal')
->orderBy('idCiclo', 'DESC')
->take(1)
->get();
First in both queries you have errors both in logic and in results. As for the first you can give completely erroneous results, not necessarily the id with maximum value corresponds to the last record. In your second query the error is thatyour variable $buscar is a collection type and not a string, that's why the error.
I suggest you do like this:
$ultimo = DB::table('ciclo')
->select('idCiclo','fechaFinal')
->orderBy('idCiclo', 'desc')
->limit(1)
->get();

Use `AND` in Laravel Query Builder, syntax error (orOn)

I have this sql (MariaDB) query, it works ok:
SELECT
admin_combustibles.nombre,
admin_combustibles.id_combustible,
admin_combustible_unidades.nombre AS unidades,
admin_tipo_combustibles.nombre AS tipo_combustible,
admin_indice_combustibles.valor_combustible
FROM
admin_combustibles
INNER JOIN admin_combustible_unidades ON admin_combustibles.combustible_unidades_id = admin_combustible_unidades.id_combustible_unidad
INNER JOIN admin_tipo_combustibles ON admin_combustibles.tipo_combustible_id = admin_tipo_combustibles.id_tipo_combustible
LEFT JOIN admin_indice_combustibles ON admin_combustibles.id_combustible = admin_indice_combustibles.combustible_id
AND admin_indice_combustibles.anio = 1992
AND admin_indice_combustibles.mes = 6
ORDER BY
admin_combustibles.nombre
But when I try to make it through Laravel, I have some error because Laravel put some on the number 1992, in that way the query doesn't work.
Plus, I don't know how to do the AND on Laravel, I only have orOn but it doesn't work:
$datos = AdminCombustible::select([
'admin_combustibles.nombre',
'admin_combustibles.id_combustible',
'admin_combustible_unidades.nombre AS unidades',
'admin_tipo_combustibles.nombre AS tipo_combustible',
'admin_indice_combustibles.valor_combustible'])
->join('admin_combustible_unidades', 'admin_combustibles.combustible_unidades_id', '=', 'admin_combustible_unidades.id_combustible_unidad')
->join('admin_tipo_combustibles', 'admin_combustibles.tipo_combustible_id', '=', 'admin_tipo_combustibles.id_tipo_combustible')
->leftJoin('admin_indice_combustibles', function ($join) {
$join->on('admin_indice_combustibles.combustible_id', '=', 'admin_combustibles.id_combustible')->orOn('admin_indice_combustibles.anio', '=', 1992);
})
->get();
dd($datos);
I got an sql syntax error.
Any help on how to make that query with query builder of Laravel? (I put the entire query as DB::raw and it works, but I don't want to use raw() )
I think there might be two problems here. Since you are using and in your original query, you might be needing to use or instead of orOn on your join.
Also you will need to use DB::raw() on the parameters, otherwise Laravel will consider them columns....
$join->on('admin_indice_combustibles.combustible_id', '=', 'admin_combustibles.id_combustible')->on('admin_indice_combustibles.anio', '=', DB::raw('1992'));

Translate Laravel function to SQL request to test

I would like to test the output of Laravel function in MySQL, for this I need to translate the code to SQL request.
Function :
return DB::table('products')
->leftJoin('product_locations', 'products.id', '=', 'product_locations.productId')
->select(DB::raw('IF(product_locations.id is not null,concat(product_locations.id,"-","M"),concat(products.id,"-","N")) as id'), DB::raw('IF(product_locations.id is not null,1,0) as multilocation'), 'products.productName', 'products.productName as text', 'product_locations.productLocationName', 'product_locations.binLocationName', 'product_locations.unitCost', 'product_locations.amount')
->orderBy('products.productName')
->distinct()
->get();
Use query logging:
DB::connection()->enableQueryLog();
DB::table('products')
->leftJoin('product_locations', 'products.id', '=', 'product_locations.productId')
->select(DB::raw('IF(product_locations.id is not null,concat(product_locations.id,"-","M"),concat(products.id,"-","N")) as id'), DB::raw('IF(product_locations.id is not null,1,0) as multilocation'), 'products.productName', 'products.productName as text', 'product_locations.productLocationName', 'product_locations.binLocationName', 'product_locations.unitCost', 'product_locations.amount')
->orderBy('products.productName')
->distinct()
->get();
dd(DB::getQueryLog())
It is not the way, but still you can get the same result with less effort.
Make a small mistake in you query, for example use remove last character of a table name or a column name. Then it raise an error that shows the query. Then you can easily get your query on the screen.
In your query, use product instead of products. This will cause an error in query and display it.