Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert SQL to Doctrine with LEAST and GREATEST functions

I need your help on how am I going to convert the following Mysql to Doctrine.

select * from calendar_data as c where LEAST(c.end, end) - GREATEST(c.start, start) > 0;

I tried this one:

$qb = $em->createQueryBuilder();
$query = $qb->select('items')
                ->from('\Admin\Entity\CalendarData','items')
                ->where('LEAST(items.end, :end) - GREATEST(items.start, :start) > 0')
                ->setParameter('start',$start)
                ->setParameter('end', $end);

(Given that $start and $end is already provided)

and I have the following error:

{
 "type": "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html",
 "title": "Internal Server Error",
 "status": 500,
 "detail": "[Syntax Error] line 0, col 57: Error: Expected known function,   got 'LEAST'"
}

How should I do that?

This is the generated sql to my question:

Mysql query to determine if the given datetime is included in the datetime interval

like image 745
G. Curs Avatar asked Oct 14 '25 08:10

G. Curs


1 Answers

Use Beberlei's DoctrineExtensions to extend DQL with many more MySQL functions such as GREATEST and LEAST.

  1. Install the library => composer require beberlei/DoctrineExtensions
  2. Add the functions you need to your config.yml

    doctrine:
        orm:
            dql:
                string_functions:
                    least: DoctrineExtensions\Query\Mysql\Least
                    greatest: DoctrineExtensions\Query\Mysql\Greatest
    

After installing and linking, your first try at converting the code should work as expected:

$qb = $em->createQueryBuilder();
$query = $qb->select('items')
                ->from('\Admin\Entity\CalendarData','items')
                ->where('LEAST(items.end, :end) - GREATEST(items.start, :start) > 0')
                ->setParameter('start',$start)
                ->setParameter('end', $end);
like image 185
Eric Amshukov Avatar answered Oct 16 '25 23:10

Eric Amshukov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!