2014-09-25 89 views
0

我有一些麻煩與兩個協會一個型號.. 小PIC使我的問題,希望更清楚一點..CakePHP的:一個型號多種關係

http://imgur.com/hxL06u2(對不起,我不能在這裏發佈圖片)

所以我有用戶誰可以寫/自己的文章..一個用戶可以寫多篇文章和一篇文章只能由一個用戶擁有(有很多)..

現在的用戶可以喜歡從其他用戶的文章。 ..這是一個擁有和屬於很多關係..我的問題是,當我創建一個文件sql轉儲:

Cannot add or update a child row: a foreign key constraint fails (`xxx`.`articles_users`,... 

所以蛋糕使用錯誤的關係(HABTM而不是有很多),因此錯誤的表(article_users而不是物品)

我可以寫我自己保存的查詢與右表(I」我試過這個和它的作品),但我認爲這不是最好的解決方案..

確實有人知道更好的方法?謝謝!

編輯:

文章型號

Ownes:

public $belongsTo = array(
     'User' => array(
      'className' => 'User', 
      'foreignKey' => 'user_id', 
      'conditions' => '', 
      'fields' => '', 
      'order' => '' 
     ) 
    ); 

喜歡:

public $hasAndBelongsToMany = array('User' => array( 
      'className' => 'User', 
      'joinTable' => 'articles_users', 
      'foreignKey' => 'article_id', 
      'associationForeignKey' => 'user_id', 
      'unique' => 'keepExisting', 
      'conditions' => '', 
      'fields' => '', 
      'order' => '', 
      'limit' => '', 
      'offset' => '', 
      'finderQuery' => '', 
      'deleteQuery' => '', 
      'insertQuery' => '' 
     ) 
    ); 

用戶模型

public $hasMany = array(
    'Article' => array(
     'className' => 'Article', 
     'foreignKey' => 'user_id', 
     'dependent' => false, 
     'conditions' => '', 
     'fields' => '', 
     'order' => '', 
     'limit' => '', 
     'offset' => '', 
     'exclusive' => '', 
     'finderQuery' => '', 
     'counterQuery' => '' 
    ) 
); 

    public $hasAndBelongsToMany = array(
    'Article' => array(
     'className' => 'Article', 
     'joinTable' => 'articles_users', 
     'foreignKey' => 'user_id', 
     'associationForeignKey' => 'article_id', 
     'unique' => 'keepExisting', 
     'conditions' => '', 
     'fields' => '', 
     'order' => '', 
     'limit' => '', 
     'offset' => '', 
     'finderQuery' => '', 
     'deleteQuery' => '', 
     'insertQuery' => '' 
    )); 
+1

爲您的用戶和文章型號分享相關型號代碼($ hasMany,$ belongsTo,HABTM) – AgRizzo 2014-09-25 20:05:11

回答

0

在用戶模式,你的關係名稱/別名是相同的:文章。讓他們不同。 根據documentation但是,每個模型的別名在整個應用程序中必須是唯一的。

+0

哦,男人這麼簡單...謝謝! – tobysas 2014-09-26 10:58:52