CakePHP为不同类型的评论制作子模型

时间:2012-02-29 16:18:31

标签: cakephp inheritance model cakephp-1.2

我有一个Comment模型,用于存储GoalNote的评论。

当前的实施有一个GoalComment模型和一个NoteComment模型,每个模型extends CommentComment的{​​{1}}执行以下操作:

beforeFind

基本上将$queryData['conditions'][$this->name . '.' . $this->__type_field] = $this->name; 模型的type字段设置为CommentGoalComment,具体取决于哪些类正在执行NoteComment

这个实现到现在为止,我想要删除注释。以下是目标中的评论模型关联:

find

在我的beforeDelete中,我想删除与目标相关的所有评论,我有:

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

但是我收到以下SQL错误:

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

这是因为我之前描述的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'中的beforeFind,然后将Comment关系重新制作为:

$hasMany

这会从var $hasMany = array( 'Comment' => array( 'className' => 'Comment', 'foreignKey' => 'object_id', 'conditions' => array('Comment.type = "GoalComment"') ) ); 模型中提取所有想法,对我来说这似乎更自然。

您是否有更好的实施方案,或者我应该选择上面的那个?谢谢!

1 个答案:

答案 0 :(得分:4)

我认为你认识到自己过度思考这些联想是正确的。

此类关系的“正常”方式是在评论表中使用字段modelforeign_key

//Comment model
public $belongsTo = 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')
    )
);