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

标签 cakephp inheritance model cakephp-1.2

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

当前实现有一个 GoalComment 模型和一个 NoteComment 模型,每个模型都扩展 CommentComment code> 的 beforeFind 执行以下操作:

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

它基本上将 Comment 模型的 type 字段设置为 GoalCommentNoteComment,具体取决于哪个这些类中的一个正在执行查找

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

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'。这让我重新思考应对这种情况的整个方法。

所以我的问题是应该如何重新实现这种关系?我最好的想法是废弃 Comment 中的 beforeFind 并简单地将 $hasMany 关系重新设置为:

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

这将从Comment模型中提取所有的想法,对我来说这似乎更自然。

您有更好的实现方案吗?还是我应该采用上面的方案?谢谢!

最佳答案

我认为您正确地认识到您对这些关联的思考过度了。

这种类型关系的“正常”方式是简单地使用评论表中的字段 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')
    )
);

关于CakePHP 为不同类型的评论制作子模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9502745/

相关文章:

mysql - CakePHP LEFT JOIN 在有条件的多个表上

php - CakePHP 错误数据库未定义

C++ 继承问题,错误 LNK1120 和 LNK2019

python - 为什么我得到 python manage.py syncdb 的错误 (IndentationError : unexpected indent)

php - CakePHP:如何从一个唯一字段切换两个行值?

mysql - 在 CakePHP 中使用 OR 时返回不匹配的记录

database - ERD图中使用的继承符号是什么?

c# - 抽象类的派生类中的额外方法

Django:为可重用的模型字段创建 Mixin

mysql - Propel 1.6 如何在 symfony2 中自动生成 Base/Peer/Query 模型类