2012-02-29 66 views
2

我有一個Comment我正在使用該模型來存儲Goal s和Note s的註釋。CakePHP爲不同類型的評論製作兒童模型

當前的實現具有GoalComment模型和NoteComment模型,其中每個extends Comment,並且CommentbeforeFind執行以下操作:

$queryData['conditions'][$this->name . '.' . $this->__type_field] = $this->name; 

基本上設置Comment模型的type場要麼GoalCommentNoteComment,這取決於哪些類正在執行find

這個實現已經運行到現在,我想刪除評論。下面是模特協會註釋在目標:

var $hasMany = array(
    'Comment' => array(
     'className' => 'GoalComment', 
     'foreignKey' => 'object_id' 
    ) 
); 

而且在我beforeDelete,在這裏我想刪除與目標相關聯的所有意見,我有:

$this->Comment->deleteAll(array('object_id' => $this->id)); 

,但我得到了下面的SQL錯誤:

SQL Error: 1054: Unknown column 'GoalComment.type' in 'where clause' [CORE\cake\libs\model\datasources\dbo_source.php, line 525] 
Query: SELECT `Comment`.`id` FROM `comments` AS `Comment` LEFT JOIN `users` AS `Poster` ON (`Comment`.`poster_id` = `Poster`.`id`) 
LEFT JOIN `goals` AS `Goal` ON (`Comment`.`object_id` = `Goal`.`id`) 
WHERE `object_id` = 52 AND `GoalComment`.`type` = 'GoalComment' 

這是因爲beforeFind動作發生之前我所描述的,它增加了GoalComment.type = 'GoalComment'。這使我重新思考了這種情況的整個做法。

所以我的問題是應該如何重新實現這種關係?我的最好的辦法是廢鋼CommentbeforeFind,只是翻拍$hasMany關係是:

var $hasMany = array(
    'Comment' => array(
     'className' => 'Comment', 
     'foreignKey' => 'object_id', 
     'conditions' => array('Comment.type = "GoalComment"') 
    ) 
); 

這將提取所有從Comment模式的思維,它只是似乎更自然的我。

您是否有更好實施的想法,還是應該使用上面的方法?謝謝!

回答

3

我認爲你是正確的認識到你一直在過度考慮這些關聯。

對這種關係的「正常」的方式是在你的意見表中簡單地使用領域modelforeign_key

//Comment model 
public $belongTo = array(
    'Goal' => array(
     'className' => 'Goal', 
     'foreignKey' => 'foreign_key', 
     'conditions' => array('Comment.model' => 'Goal') 
    , 
    'Note' => array(
     'className' => 'Note', 
     'foreignKey' => 'foreign_key', 
     'conditions' => array('Comment.model' => 'Note') 
    ) 
); 

//Goal model 
public $hasMany = array(
    'Comment' => array(
     'className' => 'Comment', 
     'foreignKey' => 'foreign_key', 
     'conditions' => array('Comment.model' => 'Goal') 
    ) 
); 

//Note model 
public $hasMany = array(
    'Comment' => array(
     'className' => 'Comment', 
     'foreignKey' => 'foreign_key', 
     'conditions' => array('Comment.model' => 'Note') 
    ) 
); 
+0

太棒了,謝謝!這就是我的想法,減去美元**的**。但是,這個問題並不是我開始的。這就是爲什麼這是額外的硬哈哈!修復其他人的代碼總是一個冒險。 – Garrett 2012-02-29 17:50:45

+0

很高興提供幫助。我完全理解與其他人的代碼一起工作的「樂趣」。 – Dave 2012-02-29 17:53:52

+0

存在着[開心]的某些奇怪的定義(http://dwarffortresswiki.org/index.php/Losing)。 – 2012-02-29 18:42:41