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
Related
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();
I am trying to build an app like airbnb using Symfony 4. I have properties that are listed by users and reservations for these properties. The relation between those entities is OneToMany. One property to many reservations. Each reservation has a start_date and an end_date. I want to run a query that returns all properties that are not taken for certain dates selected by users. My query so far is like this:
->andWhere('NOT (reservations.startDate BETWEEN :checkInDate AND :checkOutDate) AND ' .
'NOT (reservations.endDate BETWEEN :checkInDate AND :checkOutDate) AND ' .
'NOT (reservations.startDate <= :checkInDate AND reservations.endDate >= :checkOutDate)')
->setParameter('checkInDate', new \DateTime($checkIn))
->setParameter('checkOutDate', new \DateTime($checkOut))
->innerJoin('p.reservations', 'reservations');
However this seems to check only the first reservation that shows up in the database for each property and ignores the rest. How can I write the code so that the query checks all reservations made for a property not just the first one in the database. Thank you so much
I figured it out. I created another query for reservations that are not overlapping with the dates selected by users and then used notIn in the property query to get all properties which do not have such reservation. Here is the code. This is the query for the reservations:
$subQueryBuilder = $this->getEntityManager()->createQueryBuilder();
$subQuery = $subQueryBuilder
->select('prop.id')
->from('App:Reservation', 'reservation')
->orWhere('reservation.startDate BETWEEN :checkInDate AND :checkOutDate')
->orWhere('reservation.endDate BETWEEN :checkInDate AND :checkOutDate')
->orWhere('reservation.startDate <= :checkInDate AND reservation.endDate >= :checkOutDate')
->andWhere('reservation.confirmedAt IS NOT NULL')
->andWhere('reservation.rating IS NULL')
->innerJoin('reservation.property', 'prop')
;
And this is the query for the properties which returns only properties which are not found in the first query. It uses the property id to check that.
$properties = $this->createQueryBuilder('p')
->select('p')
->andWhere('p.approved = 1')
->andWhere($properties->expr()->notIn('p.id', $subQuery->getDQL()))
->andWhere('reservations.confirmedAt IS NOT NULL')
->andWhere('reservations.rating IS NULL')
->setParameter('checkInDate', new \DateTime($checkIn))
->setParameter('checkOutDate', new \DateTime($checkOut))
->innerJoin('p.reservations', 'reservations')
->getQuery();
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();
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()
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()