【问题标题】:Unique Ids in Join table symfony2连接表 symfony2 中的唯一 ID
【发布时间】:2013-09-20 16:23:36
【问题描述】:

我有两个实体产品和类别,我已经成功地创建了一个多对多关系,因此创建了一个新表,如下所示:

┌────────────────┐         ┌───────────────────┐         ┌────────────────┐
|  products      |         | product_categories|         |     categories |
├────────────────┤         ├───────────────────┤         ├────────────────┤
| id#            ├---------┤ product_id        |    ┌----┤ id#            |
| --             |         | cat_id            ├----┘    | --             |
| --             |         |                   |         |                |
└────────────────┘         └───────────────────┘         └────────────────┘

类别

  /**
 * @ORM\ManyToMany(targetEntity="Products", mappedBy="category")
 */
protected $product;

产品

 /**
 * @ORM\ManyToMany(targetEntity="categories", inversedBy="product")
 * @ORM\JoinTable(name="product_categories",
 *      joinColumns={@ORM\JoinColumn(name="product_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="cat_id", referencedColumnName="id")}
 *      )
 **/
protected $category;

现在我希望产品和 cat_id 在 product_categories 表中是唯一的。怎么做?

【问题讨论】:

  • targetEntity="categories" 应该是大写。但我认为这不是问题的原因。您能否从您的 mysql 控制台粘贴“SHOW CREATE TABLE product_categories”的结果(我没有问,但我假设您使用 mysql 对吗?)?
  • 当然,我唯一不确定的是,我必须手动在数据库(mysql)级别创建复合键还是注释会处理它???
  • 教义应该处理它。
  • 实际上,我已经手动创建了实体和表,并且刚刚使用命令生成了 getter 和 setter。现在,我已经为 product_category 表创建了一个复合键约束,并添加了一个 try catch 代码处理重复条目。现在我想要的一切都实现了。这是正确的做法吗??
  • 不,这是个糟糕的主意!使用原则来处理您的数据库模式。我已经编辑了我的答案,以展示你应该如何做到这一点。干杯

标签: php symfony doctrine-orm


【解决方案1】:

如果您隐式指定多对多关系,例如通过注释 (@ManyToMany),Doctrine 将创建包含两个字段的复合主键:product_id 和 cat_id,因此您可以保证它是唯一的。

如果您通过附加实体(比如ProductCategories)明确指定多对多关联,则可以添加 UniqueEntity 约束。

UniqueEntity constraint documentation

带注释的示例:

use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity
 * (...)
 * @UniqueEntity(fields={"product_id", "cat_id"})
 */
class ProductCategories {
    // (...)

编辑:

此外,请确保您已正确生成数据库。您应该使用 Doctrine 的命令来执行此操作(不要手动执行!):

php -f ./app/console doctrine:database:drop
php -f ./app/console doctrine:database:create
php -f ./app/console doctrine:schema:create 

这样,Doctrine 将根据您的实体创建适当的数据库架构。如果您将来要更改任何内容(在您的实体中),您将能够更新您的架构:

php -f ./app/console doctrine:schema:update --force

(对于上述大多数命令,您还可以添加--dump-sql 参数,这会导致仅显示 sql 而不是更改数据库)

【讨论】:

  • 好吧,我已经通过注释生成了关系,但不幸的是,它接受了重复的条目..
  • 嗯,这很奇怪。我在 Symfony 2.1 到 2.3 的许多项目中都使用了 ManyToMany,它总是创建禁止重复条目的复合主键。你能说明你是如何定义这种关联的吗?可能有什么问题
猜你喜欢
  • 2022-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-18
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
相关资源
最近更新 更多