如何在一个可以具有不同值的属性上查找

Uma*_*r3x 5 php doctrine symfony

我正在尝试显示一个表格,用户将在表格中通过选择不同的选项来决定显示哪些对象。

 if ($form->isValid()) {
        $type = $form->get('type')->getData();
        //Getting values from Array $type returned by getData on the form
        foreach ($type as $livraison) {

            $elements = $this->getDoctrine()
                    ->getManager()
                    ->getRepository('etaqenregistrementBundle:Livraison')
                    ->findBy(array('type' => $livraison));
        }

    }
Run Code Online (Sandbox Code Playgroud)

如果我们选择了两个选项, $type 将是一个包含两个不同对象 $livraison 的数组在 foreach 语句中为var_dump($livraison)):

对象(etaq\adminBundle\Entity\typeLivraison)[434] private 'id' => int 1 private 'valeur' => string 'Interne'(长度=7)

对象(etaq\adminBundle\Entity\typeLivraison)[436] private 'id' => int 3 private 'valeur' => string 'Autorité' (length=9)

但是 findBy 方法只返回一个对象,即表单中第一个被选中的对象。

如果用户在表单中选择了一个参数,我想要的是对一个参数进行排序,或者如果他选择了两个或三个,则对两个参数进行排序......等等

这是我的表格:

    $form = $this->createFormBuilder()
            ->add('ecart', 'choice', array(
                'label' => 'Only late :',
                'choices' => array(true => 'Yes', false => 'No'),
                'multiple' => false,
                'expanded' => true,
                'required' => true,
                'empty_data' => false))
            ->add('type', 'entity', array(
                'label' => ' Type :',
                'class' => 'etaqadminBundle:typeLivraison',
                'empty_data' => false,
                'required' => true,
                'property' => 'valeur',
                'multiple' => true,
                'expanded' => true))
            ->getForm();
Run Code Online (Sandbox Code Playgroud)

谢谢你们。

小智 4

findBy 可以返回多个值:

如果传递值数组,Doctrine 会自动将查询转换为 WHERE 字段 IN (..) 查询: Doctrine 2 Docs。

获取所有 id,然后将它们全部发送到 findBy 中。

if ($form->isValid()) {
        $type = $form->get('type')->getData();
        $livRaisonsIds = array();
        //Getting values from Array $type returned by getData on the form
        foreach ($type as $livraison) {
             // Something similar, there might be a setter to get the id since its private.
             $livRaisonsIds[] = $livraison->id;                 
        }

        $elements = $this->getDoctrine()
                ->getManager()
                ->getRepository('etaqenregistrementBundle:Livraison')
                ->findBy(array('type' => $livRaisonsIds));
}
Run Code Online (Sandbox Code Playgroud)