Doctrine ManyToMany具有特定的字段值

时间:2017-08-23 15:46:51

标签: symfony doctrine-orm many-to-many

我正在尝试使用依赖于字段值的doctrine(在symfony中)创建关系ManyToMany。

/**
 * @ORM\ManyToMany(targetEntity="Label")
 * @ORM\JoinTable(
 *      name="Item_Label",
 *      joinColumns={@ORM\JoinColumn(name="item_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="label_id", referencedColumnName="id")}
 * )
 */
private $labels;

我们了解到,我们必须通过表Label

Item_label获取数据

我们在Wine

的桌子上

Wine.id <-> Item_Label.item_id

         <<< `WHERE Item_Label.item_type = 'wine'` >>>
                                   `Item_Label.label_id` <-> `Label.id`

那么,我怎么能在注释中写WHERE Item_Label.item_type = 'wine'? 或者是SqlFilter(我试过但失败了)?

感谢您的帮助=)

1 个答案:

答案 0 :(得分:0)

所以,从this SO answer来看似乎在学说中是不可能的。

我的解决方法是向我的实体类添加一个方法,如下所示

public function foo($itemLabelRepo)                             
{                                                                          
    $found = $itemLabelRepo->findBy(['item_type'=>'wine', 'label_id'=>$this->getId()]);
    if(count($found)!=1) {                                                 
      throw new \Exception("Found non-one object from entity role");       
    } 
    return $found[0];                                                      
}   

其中$ itemLabelRepo将是您案例中“Item_Label”的存储库