Find By Date Laravel 5.2 - php

I have some problem with searching by existing date.
In Model:
$date = '2016-01-14';
public static function getByDate($date)
{
$query = self::select('date', DB::raw('SUM(test_count) as test'))
->whereDate('date', '=', $date)
->groupBy('date')
->orderBy('date', 'ASC')
->get();
}
But I didn't get a result, because this code creates SQL:
select `date`, SUM(test_count) as test from `test_table` where date(`date`) = 2016-01-14 group by `date` order by `date` asc limit 1
Not quoted around of date => 2016-01-14
How to fix it?
I try to use whereRaw with params, for example:
return $query->whereRaw("date= ?",[$date]);
but it did not help...

You need to change the ->whereDate('date', '=', $date) to this:
->where('date', '=', $date)
Or you can use this:
->whereDate($date)
So, it's obvious that, you can use either ->whereDate($date) or ->where('date', '=', $date) because whereDate is a dynamic method and in this case, it'll become: where('date', '=', $date).

Related

Create subquery in NOT IN

I am using Laravel Framework 6.16.0.
I have the following sql query:
SELECT DISTINCT
`companies`.*
FROM
`companies`
LEFT JOIN `trx` ON `trx`.`companies_id` = `companies`.`id`
WHERE
`trx`.`transaction_date` >= 2020-11-12 AND companies.symbol NOT IN (SELECT DISTINCT
companies.symbol
FROM
`companies`
LEFT JOIN articles a ON a.companies_id = companies.id
WHERE
a.created_at >= 2020-11-12
ORDER BY
created_at
DESC)
ORDER BY
transaction_date
DESC
I have created the following eloquent query:
DB::connection('mysql_prod')->table('companies')->select('companies.symbol')
->leftJoin('trx', 'trx.companies_id', '=', 'companies.id')
->where('trx.transaction_date', '>=', Carbon::today()->subDays(1)->startOfDay())
->orderBy('transaction_date', 'desc')
->distinct()
->get('symbol');
However, I am not sure how to pack the in my eloquent query to get all the symbol back that should be excluded.
I highly appreciate your replies!
You should try something like this:
$date = Carbon::today()->subDays(1)->startOfDay();
DB::connection('mysql_prod')->table('companies')->select('companies.symbol')
->leftJoin('trx', 'trx.companies_id', '=', 'companies.id')
->where('trx.transaction_date', '>=', $date)
->whereNotIn('companies.symbol', function ($q) use ($date) => {
$q->select('companies.symbol')
->from('companies')
->leftJoin('articles', 'articles.companies_id', 'companies.id')
->where('articles.created_at', '>', $date)
->distinct()
->get()
})
->orderBy('transaction_date', 'desc')
->distinct()
->get();
It will provide a similar query as you mentioned.
Reference from here.
Also, you can read how to write sub Query from Laravel docs.
Check this one more good answer for that what you need.

Laravel datetime created_at

I have a question. If created_at in my database is datetime and I want to make a query like this
whereDate('created_at', '=', date('Y-m-d'))
I get nothing as a result. How can i handle this situation ?
Another case: I want
whereDate('created_at', '=', date('M'))
You can use other helper functions maybe:
$query->whereYear('created_at', '=', date('Y'))
->whereMonth('created_at', '=', date('m'))
->whereDay('created_at', '=', date('d'));
Assuming you are using MySQL, you could use whereRaw:
whereRaw('created_at = CURDATE()')
For your second case:
whereRaw("month_name = DATE_FORMAT(CURDATE(), '%b')")
First Query: You can use Carbon specifying date format (date without time toDateString() / date with time toDateTimeString() ).
$query->whereDate('created_at', '=', Carbon::today()->toDateTimeString());
Second Query: Just query on whereMonth
$query->whereMonth('created_at', '=', date('m'));

Laravel - select row between start date and end date using eloquent

I want to convert this query into laravel eloquent,
select * from schedule where (now() between start_date and end_date);
I tried using whereBetween, but I got some error.
$schedule = Schedule::whereBetween(Carbon::now(), ['start_date', 'end_date'])->get();
the error looks like this
QueryException in Connection.php line 647:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '2017-06-01 06:17:30' in 'where clause' (SQL: select * from schedule where 2017-06-01 06:17:30 between start_date and end_date)
any idea?
$from = $request->from;
$to = $request->to;
$title="Sales From: ".$from." To: ".$to;
$sales = Sale::whereBetween('created_at', [$from.' 00:00:00',$to.' 23:59:59'])->get();
$schedule = Schedule::where('start_date', '<=', Carbon::now())
->where('end_date', '>=', Carbon::now())
->get();
Or
$schedule = Schedule::whereRaw('(now() between start_date and end_date)')->get();
The whereBetween is used only when you want to find a row where a single column is between 2 values, what you want to do is :
$now = Carbon::now();
$schedule = Schedule::where('start_date', '<=', $now)
->where('end_date', '>=', $now)
->get();
whereBetween should used like this, ->whereBetween('loc_lng', array(-0.24272918701172, -0.24272918701172)) whose first parameter is the column name, and the second is the region.
In you situation you can use ->where('start_date', '<' Carbon::now())->where('end_date', '>' Carbon::now());
You can use whereBetween('date_field',[$from_date, $to_date]) to fetch the data between two dates but it should be in the array format.
$products = Sale::with('products')
->whereBetween('date',[$from_date, $to_date])
->get();
return response()->json($products);
You can also use whereBetween(whereBetween('date_field',[$from_date, $to_date])) with multiple where conditions like:
$products = Sale::with('products')
->whereBetween('date',[$from_date, $to_date])
->where(function ($query) use ($search) {
$query->where('employee_id', 'like', '%'.$search.'%')
->orWhere('employee_name', 'like', '%'.$search.'%');
})
->get();
return response()->json($products);
I hope this will work for you :)

Laravel equivalent query builder

How to convert below query into Laravel equivalent query builder
SELECT * FROM `table_name` WHERE '03-05-2017 09:30' BETWEEN `start_date` AND `end_date` AND `who_should`='VV000'
I tried using whereBetween but not working as expected.
$given_time = "03-05-2017 09:30";
\DB::table('table_name')
->whereRaw(" '$given_time' Between start_date and end_date ")
->where("who_should", "=", "VV000")
->get();
$date = new Carbon\Carbon('03-05-2017 09:30');
$date_string=$date->toDateTimeString();
$data_set = DB::table('table_name')
->select(DB::raw('*'))
->where('start_date', '<', $date_string )
->where('end_date', '>', $date_string )
->where('who_should','=','VV000')
->get();
Try above code

How can I use the sentence "Order By Hour" in Laravel 4?

I'm trying to order my query by hour, but I don't know how to do it. In MySql will be:
ORDER BY HOUR(FechaTermino) // FechaTermino = Timestamp... (dd/mm/yy hh:mm:ss)
but in laravel??
this is my Query Builder
$servicios = DB::table('Servicio_Tecnico')
->join('Servicio', 'Servicio_Tecnico.Servicio_idServicio', '=', 'Servicio.idServicio')
->join('Tecnico', 'Servicio_Tecnico.Tecnico_idTecnico', '=', 'Tecnico.idTecnico')
->whereRaw('DAY(Servicio.FechaTermino) = ?', array($dia))
->where('Servicio.Completado', '=', '1')
->orderBy('FechaTermino', 'Desc')
->paginate(10);
Just use a raw query:
->orderBy(DB::raw('HOUR(FechaTermino)'))
Check this answer, very similar.

Categories