2010-05-19 37 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自己。所以這取決於你的目標是否會降低。

相關問題