gpt4 book ai didi

symfony - 没有主 ID 键的多对一 Doctrine

转载 作者:行者123 更新时间:2023-12-03 23:23:16 26 4
gpt4 key购买 nike

我正在尝试在我的数据库中的 2 个实体之间设置 FK。父表与子表具有多对一关系。由于外部进程填充子表的方式(父进程永远不知道子进程的主 ID),我无法使用普通的 parent_id => id FK 加入这些表。

Doctrine 接受如下所示的实体,但 Mysql 在尝试将 FK 添加到表时失败,并出现以下错误。
ALTER TABLE parent_tbl ADD CONSTRAINT FK_1172A832F85E0677 FOREIGN KEY (username) REFERENCES child_tbl (username);SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`dmname`.`#sql-f16_d8acf`, CONSTRAINT `FK_1172A832F85E0677` FOREIGN KEY (`username`) REFERENCES `child_tbl` (`username`))

class Parent
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;


/**
* @ORM\ManyToOne(targetEntity="Child")
* @ORM\JoinColumn(name="username", referencedColumnName="username", nullable=false)
*/
protected $username;

// ...
}

class Child
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*
* @var integer
*/
protected $id;

/**
* @ORM\Column(type="string", unique=true)
*
* @var string
*/
protected $username;

// ....
}

最佳答案

来自 the Doctrine limitations and known issues :

It is not possible to use join columns pointing to non-primary keys.
Doctrine will think these are the primary keys and create lazy-loading proxies with the data, which can lead to unexpected results.
Doctrine can for performance reasons not validate the correctness of this settings at runtime but only through the Validate Schema command.



所以,如果你运行 doctrine:schema:validate命令,你应该得到类似的东西:

[Mapping] FAIL - The entity-class Parent mapping is invalid:
* The referenced column name 'username' has to be a primary key column on the target entity class Child.



我希望您找到一种解决方法,使用主键作为连接列来保持逻辑完整。

关于symfony - 没有主 ID 键的多对一 Doctrine ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35848605/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com