Latest Value for each day - Laravel Eloquent - php

Anyone can help to put this into a Laravel Eloquent statement ?
where timestamp = unix timestamp
SELECT max(timestamp) ,value FROM `forex` group by FROM_UNIXTIME(timestamp,'%Y%m%d' )

Try this:
DB::table('forex')
->selectRaw('MAX(forex.TIMESTAMP), forex.value')
->groupByRaw('forex.TIMESTAMP, "%Y%m%d"')
->get();

Related

Laravel 5.2 Get date_diff of data each rows using eloquent method

I want to get the date difference from date today and set as reference while querying on database each rows to count the days. How to construct it in laravel-eloquent way? Thanks!
$query ="SELECT unix_timestamp(NOW()) - unix_timestamp(created_at) AS time_diff from users WHERE trial=1";
$result=mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_assoc($result))
{
$diff= $row['time_diff']
}
you can use selectRaw in laravel Query Builder
DB::table('users')
->selectRaw('unix_timestamp(NOW()) - unix_timestamp(created_at) AS time_diff')
->where('trial',1)
->get();
or you want use Eloquent
Model::select(DB::raw('unix_timestamp(NOW()) - unix_timestamp(created_at) AS time_diff'))
->where('trial',1)
->get();

Get min(date), max(date) with group by eloquent laravel

This query is for getting other data with the highest value of date with the group by/unique. Here I used unique in place of group by.
My question is how to get min(date) and max(date) with group by/unique.
The group by/unique is for Dataset table's date field.
I have searched for this but not getting exact solution that how to get max and min date with group by/unique in laravel eloquent.
In table structure, there are multiple entries for one code so here I used group by/unique to get one record for the code.
There can be multiple dates as 02-01-2003,01-03-2007,01-01-2019, 01-07-2018... etc. with same/ different code. If I group by with code then get onmy one record per code. So here I want to select the max date [01-01-2019] and min date [02-01-2003].
Thanks in advance.
Controller:
$datasets = Dataset::where('user_id', $user_id)
->orderBy('date','desc')
->get(['code', 'access','user_id','date'])
->unique('code');
Finally I got solution but this can not be the exact solution but as I am beginner and not getting the exact solution I do this functionality as below:
I created two different queries to get min and max values.
$min_datasets = Dataset::where('user_id', $user_id)
->orderBy('date','asc')
->get(['code', 'access','user_id','date'])
->unique('code');
$max_$datasets = Dataset::where('user_id', $user_id)
->orderBy('date','desc')
->get(['code', 'access','user_id','date'])
->unique('code');
Try to select max and min date like this:
$datasets = Dataset::select('code', 'access','user_id', DB::raw('MAX(date) as max_date'), DB::raw('MIN(date) as min_date'))
->where('user_id', $user_id)
->orderBy('date','desc')
->get()
->unique('code');
$data = DB::table('table_name')->where('user_id',$user_id)
->select('code','access','user_id','date')
->whereBetween('date', [02-01-2003, 01-01-2019])
->groupBy('unique_column')
->get()

Symfony get distinct months from database DateTime field

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

How to use DATE_ADD to compare date in range in Doctrine and Symfony2 using createQueryBuilder

I have two tables related to each other (main_table OneToMay detail_table). There is a deadline_days field in main table and a create_date in detail_table. I want to select all details which create_date+main.deadline_days are passed base on today date. (This was the scenario)
This is the proper MySQL query which gives me right records
SELECT `D`.* FROM `details_table` AS `D`
INNER JOIN `main_table` AS `M` ON (`D`.`Main_Id` = `M`.`id`)
WHERE DATE_ADD(`D`.`Create_Date`, INTERVAL `M`.`Deadline_days` DAY) <= NOW()
Now in Symfony when I want to create the query using createQueryBuilder it comes with this error
[Syntax Error] line 0, col 165: Error: Expected Doctrine\ORM\Query\Lexer::T_COMMA, got 'M'
This is what I have for now in my query builder
$result = $this->createQueryBuilder('D')
->join('D.Main', 'M')
->where('DATE_ADD(D.Create_Date, INTERVAL M.DeadLine_Days DAY) <= NOW()')
->getQuery()
->getResult();
Any idea how to fix this?
Thanks in advance.
Please do not suggest using native query
This is what I found base on this link (Doctrine Update DQL function signature)
Doctrine2 has function DATE_ADD but does not have INTERVAL param as MySQL, also the unit param should be as string 'DAY'; so the Query should be:
$result = $this->createQueryBuilder('D')
->join('D.Main', 'M')
->where('DATE_ADD(D.Create_Date, M.DeadLine_Days, 'DAY') <= CURRENT_DATE()')
->getQuery()
->getResult();
In doctrine we should use CURRENT_DATE() instead of NOW()

Building query with Query Builder or Eloquent in Laravel 4

I have a query that has multiple subqueries with parameters that I'm trying to build in a Laravel model.
I'm quite new to Laravel 4, so I'd really like some help with what is the "best" way to do this.
The Query that I need to reproduce is:
Select userId from facultyAvailability
where
:startDate between startDate and endDate
and :endDate between startDate and endDate
and userId NOT IN(
Select
userId
from
schedulerTrialSchedule
inner join `review`
on eventId=lectureId
where
trialId = :trialId
and (
startDate between :startDate and :endDate
or endDate between :startDate and :endDate
)
)
AND userId IN (
SELECT userId
from
faculty2FacultyCategory
where
categoryId in(:categoryIdList)
)
I'm really not sure what methods to chain together to build this. Any help would be greatly appreciated.
Well, after some trial and error, I think I arrived at the proper solution.
I am making use of Eloquent's Query Scope functionality. On the model in question, I've defined a scope as:
public function scopeAvailable($query, $trialId, UnscheduledEvent $event)
{
$query->whereRaw('? BETWEEN startDate AND endDate', array($event->startDate))
->whereRaw('? BETWEEN startDate AND endDate', array($event->endDate))
->whereIn(
'userId', function ($query) use ($trialId, $event) {
$query->select('userId')
->from('schedulerTrialSchedule')
->join('review', 'eventId', '=', 'lectureId')
->where('trialId','=',$trialId)
->where(
function ($query) use ($event) {
$query->whereBetween('startDate', array($event->startDate, $event->endDate))
->orWhereBetween('endDate', array($event->startDate, $event->endDate));
}
);
}
,'and',true);
return $query;
}
This scope yields a query that looks like:
select *
from `facultyAvailability`
where
? BETWEEN startDate AND endDate
and ? BETWEEN startDate AND endDate
and `userId` not in (
select `userId`
from `schedulerTrialSchedule`
inner join `review` on `eventId` = `lectureId`
where `trialId` = ?
and (`startDate` between ? and ? or `endDate` between ? and ?))
This is exactly what I needed it to be. I'm posting this here just for reference in case anyone else needs to know how to solve this problem.
I have to say that I'm quite impressed with Eloquent/Fluent's ability to cope do this without me having to resort to using a bunch of raw SQL. The only reason I had to use raw SQL at all is because whereBetween doesn't seem to be able to handle using a value instead of a column for the first argument of the between with columns as the second and third arguements i.e '2013-08-09' BETWEEN column1 AND column2

Categories