查询构建器在字段类型数组上添加条件

时间:2014-10-29 20:39:11

标签: symfony doctrine-orm query-builder

我的问题很简单:是否可以在字段类型数组上使用doctrine和查询构建器添加where statment?

在我的实体内部,我有以下内容:

/**
 * @var array
 *
 * @ORM\Column(name="weekDays", type="array")
 */
private $weekDays;

在对象视图中,数组如下所示:

array(
  1 => false,
  2 => false,
  3 => true,
  4 => false,
  5 => false,
  6 => false,
  7 => false
);

一旦序列化并插入到数据库中,它的表示如下所示:

a:7:{i:1;b:0;i:2;b:0;i:3;b:1;i:4;b:0;i:5;b:0;i:6;b:0;i:7;b:0;}

我试图实现的是这样的:

   $q = $this->em->getRepository('AcmeBundle:Notification')
        ->createQueryBuilder('n')
        ->andWhere('e.weekDays = :day')    <-- This is wrong
        ->setParameter('day', date('N'))
    ;

通常这会在SQL

中产生类似的结果
SELECT * FROM notification WHERE weekDays LIKE '%i:1;b:1%' -- if date('N') = 1 (monday)
SELECT * FROM notification WHERE weekDays LIKE '%i:7;b:1%' -- if date('N') = 7 (sunday)

和     SELECT * FROM notification WHERE weekDays LIKE'%i:1; b:0%' 如果我想设置->andWhere('e.weekDays != :day')

1 个答案:

答案 0 :(得分:3)

使用2.5版本的学说和3.0+的symfony,它可能看起来像:

$qb = $this->em->getRepository('AcmeBundle:Notification')
    ->createQueryBuilder('n');
$qb->where($qb->expr()->like('n.weekDays',':weekDays'))
    ->setParameter('weekDays','%i:'.date('N').';b:1%');
$results = $qb->getQuery()->getResult();

可能也有效的旧方法:

$q = $this->em->getRepository('AcmeBundle:Notification')
    ->createQueryBuilder('n')
    ->andWhere("e.weekDays LIKE '%:day%'")
    ->setParameter('day', 'i:'.date('N').';b:1')
;

如果您想将数据结构略有不同,可以将该字段分为7,因为工作日不会发生变化:

//Entity
/**
 * @ORM\Column(type="boolean")
 */
 protected $monday;

/**
 * @ORM\Column(type="boolean")
 */
 protected $tuesday;

//And so on

然后像:

$weekday = strtolower(date('l')); //Lowercase "L"
$q = $this->em->getRepository('AcmeBundle:Notification')
    ->createQueryBuilder('n')
    ->andWhere('n.'.$weekday. '= 1');