yii2 query date field with other field - php

I have a table:
id,
name,
date,
warning_days
I'm trying to query the table like this:
$result= Table::find()->where([
'<=', 'date', date('Y-m-d', strtotime('+ '.'warning_days'.' days'))])->all();
I'm fiddling with the code, but can't seem to find a way...
Can somebody, point me in the right direction?
Thanks in advance, regards, Rui

the simplest way is the use of where method in literal format based on date_add( )
$result= Table::find()
->where( 'date <= date_add( date, INTERVAL warning_day DAY)')
->all();
or you can use operator format
$result= Table::find()
->where( ['<= ', date , 'date_add( date, INTERVAL warning_day DAY)'])
->all();

Related

Laravel query by date and time

Query by date and time.
I have table with field and sample data
Schedule
--date_start = 2019-05-01
--date_end = 2019-06-30
--time_start = 08:00:00
--time_end = 10:00:00
My question is can I query it by doing select date by (current_date) if current_date is in range or in between the date_start and date end. the same also in time if time is in range
thanks in advance.
You can do it with something like this
$current = Schedule::whereDate('start_date', '<=', today())
->whereDate('end_date', '>=', today())
->whereTime('start_time', '<=', now())
->whereTime('end_time', '>=', now())
->get();
$current will be the DB records that are for now.
More information at the Docs

Having trouble getting records using Laravel

I have the following MySQL query:
SELECT COUNT(id) FROM `tblname` WHERE date >= CURDATE() - INTERVAL 1 DAY;
When I run that in MySQL it gives me the number of records for the past day.
I'm trying to do this in Laravel, because it's included in the WHMCS software I'm using, and can't really understand how to make it work.
Sometimes, when you are stuck in Laravel, just paste your SQL into a raw query like
$result = DB::select("SELECT COUNT(id) FROM `tblname` WHERE date >= CURDATE() - INTERVAL 1 DAY");
Using a query builder
$result = DB::table('tblname')
->whereDate('date', '>=', Carbon::today())
->whereDate('date', '<=', Carbon::tomorrow())
->count();
You can use carbon like
$query = DB::table('your table')->whereDate('date', '>=', Carbon::today())->whereDate('date', '<=', Carbon::tomorrow())->count();

Laravel Eloquent, group by month/year

i'm trying to group my data by month and year.
$data ->select(DB::raw('count(id) as `data`'),DB::raw('YEAR(created_at) year, MONTH(created_at) month'))
->groupby('year','month')
->get();
The output is :
{
"data": 19215,
"year": 2016,
"month": 10
},
if i group only by month, i don't know from which year belong this month, my expected output is :
{
"clicks": 19215,
"month": 11-2016,
},
{
"clicks": 11215,
"month": 12-2016,
},
i want to do it in sql, not in php.
You can try as:
->select(DB::raw('count(id) as `data`'), DB::raw("DATE_FORMAT(created_at, '%m-%Y') new_date"), DB::raw('YEAR(created_at) year, MONTH(created_at) month'))
->groupby('year','month')
->get();
Note: This is solution based on eloquent, and yes, it not the best approach, but as the question is, this is using eloquent. If you want faster way, you can do it with raw query.
If you want to group your results for example by year, you can use closure where you will parse your datetime to desired format (year or month).
Here is example of the code:
$res= ModelName::where('someColumn','test')
->get()
->groupBy(function($val) {
return Carbon::parse($val->created_at)->format('Y');
});
$result = ModelName::selectRaw('year(created_at) year, monthname(created_at) month, count(*) data')
->groupBy('year', 'month')
->orderBy('year', 'desc')
->get();
for latest version of mysql, the accepted answer will give error, so instead try
$data
->selectRaw("
count(id) AS data,
DATE_FORMAT(created_at, '%Y-%m') AS new_date,
YEAR(created_at) AS year,
MONTH(created_at) AS month
")
->groupBy('new_date')
->get();
ref: https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_date-format
The answer by #Amit Gupta is a good, but it isn't working >= MySQL 5.7/MariaDB 10.2 and calls the error:
Syntax error or access violation: 1055 Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column
To solve that issue, you can use eg. MIN() on the nonaggregated column:
->select(
DB::raw("
count(id) as data,
MIN(DATE_FORMAT(created_at, '%m-%Y')) as new_date,
YEAR(created_at) year,
MONTH(created_at) month
")
)
->groupBy('year', 'month')
->get();
$data ->select(DB::raw('count(id) as `data`'),DB::raw('YEAR(created_at) year'),DB::raw('MONTH(created_at) month'))
->groupBy(DB::raw('YEAR(created_at)'), DB::raw('MONTH(created_at)'))
->get();
=>this might help someone in 2019
$date = "2019-06-16";
return date('m', strtotime($date)); //this return you 06(edited)
so you can do foreach by this method , so you don't need to do the all sql things..

Can't replicate a DATE_FORMAT query in Laravel

So, i have this query in written out in a different version of my project.
$result = $db->select("SELECT `nID`, `txNome`, `txEmail`
FROM `".$this->tablename."`
WHERE `at_state` != 'invalid'
AND `dtCreated` < :weekAgo
AND DATE_FORMAT(dtCreated, '%w') = DATE_FORMAT(NOW(), '%w')
AND `remarketing_amigos_sent` = '1'
AND `amigo` IS NULL
AND `txEmail` NOT IN (
SELECT `email`
FROM `utils`.`unsubscribe`
WHERE `email` = `".$this->tablename."`.`txEmail`
AND (`idCampaign` = :campaign OR `idCampaign` = '*')
);
", array(
'campaign' => CoreHelper::getCampaignID(),
'weekAgo' => $aWeekAgo
));
And i'm trying to convert it for Laravel's Query Builder, i can convert the whole thing except for that DATE_FORMAT bit... I have no idea how to convert that into Eloquent.
The Application should sent e-mails once a week to a list of people, that's why the DATE_FORMAT is there, to match the weekdays.
How can i convert this into Query Builder?
My current code looks like this
$this->lead->where('at_state', '!=', 'invalid')
->where('dtCreated', '<', $aWeekAgo)
->where(???)
->where('remarketing_amigos_sent', '1')
->whereNull('amigo')
->whereNotIn('txEmail', function($q) {
$q->select('email')->from('utils.unsubscribe')->where('idCampaign', CoreHelper::getCampaignID());
})->get();
Note that the $this->lead section is intentionally different because it refers to my Eloquent Model, whereas the original version was done using the DB Facade.
You can use Laravel's whereRaw() function to accomplish some complex queries as:
->whereRaw("DATE_FORMAT(dtCreated, '%w') = DATE_FORMAT(NOW(), '%w')")
Try:
->where(DB::raw("DATE_FORMAT(dtCreated, '%w') = DATE_FORMAT(NOW(), '%w')"))
https://laravel.com/docs/5.3/database#running-queries
Hope this helps!
You may use this condition, Here I am showing an example, which I have implemented in my project.
$today = date( "Y-m-d H:i:s" );
$presentStudents = StudentAttendance::where('status_id', 1)
->where( 'DATE_FORMAT(attendance_date,\'%Y-%m-%d\'', $today )

Get data from the last 8 hours in a datetime column Eloquent

I have a query using Laravel's Eloquent and I need a where clause that will get the data from the last 8 hours since the current timestamp. I can easily do that in a raw query like:
SELECT * FROM task_tracker.tasks WHERE created_at > DATE_ADD(NOW(), INTERVAL -8 HOUR);
But how do I do that in an eloquent format? The tasks.created_at is a Datetime Format. I have this currently:
$tasks = Task::join('users', 'tasks.added_by', '=', 'users.id')
->join('users AS x', 'x.id', '=', 'tasks.assigned_to')
->select([
'tasks.id',
'tasks.task_description',
'tasks.start_timestamp',
'tasks.end_timestamp',
'tasks.status',
'users.name',
'x.name AS assign',
'tasks.created_at'
// ])->where('tasks.created_at', '>', 'DATE_ADD(NOW(), INTERVAL -8 HOUR)');
])->where(DB::raw('tasks.created_at', '=', 'DATE_ADD(NOW(), INTERVAL -8 HOUR)' ));
dd($tasks);
I tried using DB::raw and a plain encloure in a single quote (the commented line) but does not work and doesn't get any data. I am using MySQL.
DB::raw has one parameter so try whereRaw like this:
->whereRaw('tasks.created_at = DATE_ADD(NOW(), INTERVAL -8 HOUR')

Categories