2010-05-19 43 views
8

我有一个文件模型引用相同id字段,以及多(目前3)不同的其它型号(条,工作,事件),其都可以有文件,存储在文件模式。主义 - 多车型在另一个模型

的问题是,当我产生通过CLI工具表(./doctrine集结全重装),我得到这个错误信息:

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 

Ť他是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')); 
} 

我明白为什么发生这种情况(该约束不能设置多个表),但不知道我怎么能解决这个问题没有多文件表或关联表的问题。

有没有办法告诉学说,它不应该建立在文件模型的关系?

任何好主意?

+0

也许我问你为什么不使用的关联表解决呢?这是一个非常灵活和高效的解决方案,因为它允许您将相同的文件链接到不同的内容类型,而无需多次上传。与您目前的模型,这是不可能的... – wimvds 2010-05-19 14:55:54

+0

我真的可以用一个关联表解决这个问题吗?我如何让学说知道“类型”字段? – smoove 2010-05-20 08:38:48

+0

我不知道如何做到这一点教义,但问题可能在于学说添加表,它是依赖于** **之前,其他表已创建另一个表。 – 2011-03-04 23:14:45

回答

0

尝试,如果你需要,
关系:

Files: 
    type: many 
    class: File 
    local: target_id 
    foreign: id 
Files2: 
    type: many 
    class: File 
    local: id 
    foreign: id 
0

你可以尝试这样的:

columns: 
    id: { type: integer(4), notnull: true, primary: true, autoincrement: true } 
    target_id: { type: integer(4), notnull: true } 
    model:  { type: string, notnull: true } 

文件模型需要知道ID和链接入口的模型。所以,在Files.class.php你也可以指定:

public function getArticles() { 
    if (strcmp($this->getModel(), 'Articles')) { 
     return Doctrine::getTable('Articles')->findOneById($this->getTargetId()); 
    } else { 
     return false; 
    } 
} 

也许有更好的方法,但在这种情况下,你有1台,你不需要任何更多的关系,但是你必须指定干将/ setters自己。所以这取决于你的目标是否会降低。

相关问题