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 )
Related
I am actively working on a laravel project and have ran into some issues with the Query Builder. I am trying to avoid using DB::Raw but it is looking like I may need to.
$query = app($this->model());
$query = $query->select(['last_name', 'first_name', 'birthday'])
->distinct()
->leftJoin('enrollments', 'students_meta.uid', '=', 'enrollments.student_uid')
->whereIn('enrollments.type', $types)
->where('enrollments.startdate', '<=', "'{$today}'")
->where(function ($join) use ($today) {
$join->where('enrollments.dropdate', '>=', "'{$today}'")
->orWhereNull('enrollments.dropdate');
});
// todo: add viewBy filter
$query = $query->where('birth_month', '=', Carbon::today()->month);
$query = $query->orderBy('last_name')->orderBy('first_name');
$models = $query->get();
The above query builder generates the following SQL :
SELECT distinct `last_name`, `first_name`, `birthday`
FROM `students_meta`
LEFT JOIN `enrollments` ON `students_meta`.`uid` = `enrollments`.`student_uid`
WHERE `enrollments`.`type` IN ('ACTIVE', 'active')
AND `enrollments`.`startdate` <= '2019-10-29'
AND (`enrollments`.`dropdate` >= '2019-10-29' OR `enrollments`.`dropdate` IS NULL)
AND `birth_month` = 10
ORDER BY `last_name` asc, `first_name` asc;
The generated SQL is perfect based on the old code I'm moving from and produces the expected results. If I move some things around, it seems I can get the query builder to return results, but they're not the correct ones. I've looked at other questions/answers about this kind of problem and tried multiple scenarios of moving the join/changing the where's around, still no luck.
Any suggestions? (other than taking the generated sql and running it in DB::Raw()
$query = $query->orderBy('last_name')->orderBy('first_name')->get();
Your query worked fine but you didn't output it.
You can also use ->get()->toArray(); to retrieve the data in array format
Remove your quotes from around $today. The third (or second, if you eliminate the comparison operator) parameter of the where clause sends the values as a parameter in a prepared statement . So
"'{$today}'"
would look like this in a straight query:
where enrollments.startdate <= "'2019-10-29'"
So change your query to
->where('enrollments.startdate', '<=', $today)
Make sure you remove the quotes from all instances like this in your query.
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();
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();
I want to filter a table by user ID and the created_at field. The only thing is created_at is a timestamp, and I want to query by date only not time.
So something like -
$messages = Message::where(['from' => $fromUser->id, 'created_at' => 'TODAY'S DATE'])->get();
$query->whereDate('created_at', '=', date('Y-m-d'));
or
$query->whereDate('created_at', '=', Carbon::today()->toDateString());
The only way I know (in Laravel) to compare a DATE against created_at is to use whereRaw, so for your example, you'd use something like:
Message::where(...)->whereRaw('DATE(created_at) = ?', [$today])->get();
You can find more information about Eloquent and it's other methods here
Currently I have a Query Builder which gets all distinct dates from DateTime field but I need to get only distinct months and years and ignore the days. For example if dates where 2015-06-15, 2015-06-20, 2015-07-10, 2016-06-13 I should get 2015-06, 2015-07, 2016-06.
Is there any way to get this result right from database or do I need to this with php?
My current query looks like this:
$dates = $this->getEntityManager()->getRepository('EventBundle:Event')
->createQueryBuilder('e')
->select('e.startDate')
->where('e.startDate >= :startDate')
->setParameter('startDate', new DateTime('now'))
->orderBy('e.startDate', 'ASC')
->distinct()
->getQuery();
$dates = $dates->getResult();
You can get it from the database but I think you will need to use a native mysql query e.g.
select distinct(DATE_FORMAT(e.startDate,'%Y-%m'))
from event e
where e.startDate >= :startDate
To perform a native query see How to use Doctrine DBAL