使用查询构建器在Symfony2表单中进行复杂查询

时间:2013-09-05 15:37:02

标签: symfony doctrine-orm symfony-2.3

我正在尝试使用Doctrine Query Builder构建某种复杂查询,以便在表单类型中使用它们,请参阅下面的内容:

public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder
            ->add('category', 'entity', array(
                'class' => 'CategoryBundle:Category',
                'property' => 'name',
                'required' => false,
                'multiple' => true,
                'expanded' => false,
                'query_builder' => function(EntityRepository $er) {
                    $qb = $er->createQueryBuilder('c')
                            ->where($qb->expr()->eq('c.parent', '?1'), $qb->expr()->isNull('c.parent'))
                            ->setParameter(1, 0);
                }
            ))
            ->add('detail_group', 'entity', array('class' => 'ProductBundle:DetailGroup', 'property' => 'name', 'required' => false, 'multiple' => true, 'expanded' => false))
            ->add('parent', 'entity', array('class' => 'ProductBundle:ProductDetail', 'property' => 'label', 'required' => false))
            ->add('label')
            ->add('field_type', 'choice', ['choices' => \ProductBundle\DBAL\Types\FieldType::getChoices()])
            ->add('values_text', 'collection', array('type' => 'text', 'allow_add' => true, 'allow_delete' => true, 'by_reference' => false))
            ->add('description', 'text', array('required' => false))
            ->add('measure_unit', 'text', array('required' => false))
            ->add('status', 'choice', ['choices' => \ProductBundle\DBAL\Types\StatusType::getChoices()])
            ->add('to_product', 'checkbox', array('label' => 'Detalle de Stock?', 'required' => false));
}

我需要查询category表中parent=NULLparent=0的所有行,但由于我收到此错误,因此无效:

  

FatalErrorException:错误:在a上调用成员函数expr()   非对象   /var/www/html/src/ProductBundle/Form/ProductDetailType.php line   22

我做错了什么?

1 个答案:

答案 0 :(得分:2)

这是因为$qb不存在。

$qb = $er->createQueryBuilder('c');
$qb->where($qb->expr()->eq('c.parent', '?1'), $qb->expr()->isNull('c.parent'))
   ->setParameter(1, 0);