我有一个 Comment
模型,用于存储 Goal
和 Note
的评论。
当前实现有一个 GoalComment
模型和一个 NoteComment
模型,每个模型都扩展 Comment
和 Comment
code> 的 beforeFind
执行以下操作:
$queryData['conditions'][$this->name . '.' . $this->__type_field] = $this->name;
它基本上将 Comment
模型的 type
字段设置为 GoalComment
或 NoteComment
,具体取决于哪个这些类中的一个正在执行查找
。
这个实现已经运行到现在,我想删除评论。以下是目标中注释的模型关联:
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
模型中提取所有的想法,对我来说这似乎更自然。
您有更好的实现方案吗?还是我应该采用上面的方案?谢谢!
最佳答案
我认为您正确地认识到您对这些关联的思考过度了。
这种类型关系的“正常”方式是简单地使用评论表中的字段 model
和 foreign_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/