I have 2 DateTime classes in Symfony2 project. I have entity Stat, in which have $date property.
/**
* @ORM\\Column(type=\"da
A QueryBuilder is a good solution.
But you can use
->andWhere($qb->expr()->between('s.date', ':date_from', 'date_to'))
or
->andWhere($qb->expr()->andX(array(
$qb->expr()->gte('s.date', ':date_from'),
$qb->expr()->lte('s.date', ':date_to'))
)
The $qb->expr()->andX is usefull if you don't want to have some WTF when you add some andWhere or orWhere.
Here you have doctrine2 documentation for queryBuilder
You can also use setParameters method for your parameters
->setParameters(array(
'date_from' => $date_from,
'date_to' => $date_to,
))
Benjamin's answer is correct, but it lacks one detail. This is the correct way to do it:
$qb->andWhere($qb->expr()->between('s.date', ':date_from', ':date_to'));
But to set parameters, I need to do like this:
$qb->setParameter('date_from', $date_from, \Doctrine\DBAL\Types\Type::DATETIME);
$qb->setParameter('date_to', $date_to, \Doctrine\DBAL\Types\Type::DATETIME);
If I omit the DATETIME types, I get the following error (see here):
Object of class DateTime could not be converted to string
I am using Doctrine DBAL 2.0.5, this behaviour might have changed in later versions of Doctrine.
I had a similar situation. I couldn't use ->setParameter because of how my code was built, so i put this $andX variable to "catch" all the conditions founded in the foreach loop (in this case i just wrote the one with the dates because other are not relevant right now).
$this->qb = $this->em->createQueryBuilder();
$andX = $this->qb->expr()->andX();
$this->qb->select('u')
->from('models\User','u');
foreach($data as $key=>&$value){
if($key == 'date'){
$from = $this->qb->expr()->gte('u.date_from',$this->qb->expr()->literal($value['datefrom']));
$to = $this->qb->expr()->lte('u.date_to',$this->qb->expr()->literal($value['dateto']));
$condition = $from. ' AND ' .$to;
$andX->add($condition);
}
//other if
}
Notice that the parameter for this function is a multidimensional array. Hope this is helpful.