【发布时间】:2011-02-21 09:51:00
【问题描述】:
我有一个文件模型,以及多个(目前 3 个)不同的其他模型(文章、工作、事件),它们都可以有文件,存储在文件模型中。
问题是当我通过 CLI 工具 (./doctrine build-all-reload) 生成表时,我收到以下错误消息:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot
add or update a child row: a foreign key constraint fails
(`my_database/articles`, CONSTRAINT `articles_id_files_target_id`
FOREIGN KEY (`id`) REFERENCES `files` (`target_id`))
文件被定义为(此模型中未定义任何关系):
columns:
id:
primary: true
autoincrement: true
type: integer(4)
target_id: integer(4)
filename: string(255)
[...]
所有 4 个模型都有这个关系定义:
relations:
Files:
type: many
class: File
local: id
foreign: target_id
这是 Doctrine 生成的 PHP 代码(BaseFile.php):
public function setUp()
{
parent::setUp();
$this->hasOne('Publication', array(
'local' => 'target_id',
'foreign' => 'id'));
$this->hasOne('Event', array(
'local' => 'target_id',
'foreign' => 'id'));
$this->hasOne('Article', array(
'local' => 'target_id',
'foreign' => 'id'));
$this->hasOne('Job', array(
'local' => 'target_id',
'foreign' => 'id'));
}
我了解为什么会发生这种情况(无法为多个表设置约束),但不知道如何在没有多个文件表或关联表的情况下解决此问题。
有没有办法告诉 Doctrine 它不应该在 File 模型中创建关系?
有什么好主意吗?
【问题讨论】:
-
请问您为什么不使用关联表来解决它?这是一个非常灵活和高效的解决方案,因为它允许您将同一个文件链接到不同的内容类型,而无需多次上传。使用您当前的模型这是不可能的......
-
我真的可以用一个关联表来解决这个问题吗?我如何让教义知道“类型”字段?
-
我不知道如何通过教义实现这一点,但问题可能在于教义添加一个依赖于另一个表的表之前另一个表已经已创建。
-
Doctrine 需要在文件和其他模型中创建关系,以便知道表之间的关系。尝试在 Files 模型中定义关系并使用
owningSide: true指令。 doctrine-project.org/documentation/manual/1_2/en/… -
我对您在这里尝试做什么感到困惑。所有其他模型是否有一个/多个相关文件或什么?