CakePHP 2.4.2:评论模型关系 - 获取原创帖子的标题

时间:2013-04-24 20:36:16

标签: cakephp model relationship cakephp-2.1

我有一个非常典型的评论模型,其中评论属于许多其他模型,如文章,评论,照片等,反过来每个模型都有很多评论。以下是我在评论模型中建立关系的方法......

<?php
App::uses('AppModel', 'Model');

class Comment extends AppModel {

var $name = "Comment";


public $belongsTo = array(
    'User' => array(
        'className' => 'User',
        'foreignKey' => 'user_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    ),
    'Article' => array(
        'className' => 'Article',
        'foreignKey' => 'post_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    ),
    'Photo' => array(
        'className' => 'Photo',
        'foreignKey' => 'post_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    ),
    'Review' => array(
        'className' => 'Review',
        'foreignKey' => 'post_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    )
);
}

这就像一个魅力,如果我正在查看特定的文章,那么我可以从该文章中检索所有评论,并且它对其他模型的工作原理相同。 我要做的是显示所有最近的评论与原始帖子的标题无论原始帖子来自哪个模型(文章,评论,照片等),格式为{{1 }}。我认为在Comment模型的belongssto中添加以下代码会起作用,但它不会......

$comment['Original']['title']

不幸的是,如果最近的评论出现在照片 'Original' => array( 'className' => 'Article', 'foreignKey' => 'post_id', 'conditions' => array('Comment.module_id' => 3), 'fields' => '', 'order' => '' ), 'Original' => array( 'className' => 'Review', 'foreignKey' => 'post_id', 'conditions' => array('Comment.module_id' => 2), 'fields' => '', 'order' => '' ), 'Original' => array( 'className' => 'Photo', 'foreignKey' => 'post_id', 'conditions' => array('Comment.module_id' => 8), 'fields' => '', 'order' => '' ), 上,则只显示正确的标题。

2 个答案:

答案 0 :(得分:2)

您可以使用CakePHP的Containable Behavior并执行此操作:

//within a method of the Comment model
$recentComments = $this->find('all', array(
    'contain' => array(
        'Article',
        'Photo',
        'Review',
        'User'
    ),
    'limit' => 10,
    'order' => $this->alias . '.created DESC'
));

然后,您将收回评论及其父母的任何内容,无论其处于何种模式。之后,当您重复每条评论时,您可以做一个案例陈述,或者if(!empty())有点确定哪个模型有你想要展示的内容。

(旁注:根据您的“原始”尝试创建具有相同名称的多个关联不是一个好主意)

答案 1 :(得分:0)

只有条件Comment.module_id = 8才能得到评论,这并不奇怪。你犯了一个基本的PHP错误。通过多次使用相同的键Original,您每次都会有效地覆盖它的值。为每个关联选择唯一的别名(数组键)。