【问题标题】:Doctrine ManyToMany with as specific field value具有特定字段值的多对多原则
【发布时间】:2023-03-08 22:46:02
【问题描述】:

我正在尝试使用取决于字段值的学说(在 symfony 中)创建多对多关系。

/**
 * @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;

这里我们明白我们必须通过表Item_labelLabel获取数据

我们在桌子上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(我试过但失败了)?

感谢您的帮助 =)

【问题讨论】:

  • 据我所知,在ManyToMany 关系中提供您的实体定义,连接表 AKA 联结表 (Item_Label) 将只有 2 个字段,其中将包含两个相关实体的引用,其他字段不应该是在此联结表中添加了这样做,您需要创建联结实体

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


【解决方案1】:

所以,从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”的存储库

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2020-10-08
    • 2020-08-01
    相关资源
    最近更新 更多