Blog Post / Comment / User Model中的CakePHP传递关联

时间:2014-11-28 23:19:48

标签: php cakephp

我在教自己cakePHP,我对模型关联有疑问。我正在添加一个评论系统。问题出在我的帖子view()操作中,我看不到发表评论的用户,只看到FK user_id(显示看起来像“评论标题为1”)。用户有很多帖子和评论,帖子属于用户并且有很多评论,评论属于帖子和用户,如下所示:

用户

public $hasMany = array(
'Post' => array(
  'className' => 'Post',
  'foreignKey' => 'user_id'
  ),
'Comment' => array(
  'className' => 'comment',
  'foreignKey' => 'user_id'
  )
);

发表

public $belongsTo = array(
  'User' => array(
    'className' => 'User',
    'foreignKey' => 'user_id'
  )
);
public $hasMany = array(
  'Comment' => array(
     'className' => 'Comment',
     'foreignKey' => 'post_id'
  )
);

注释

public $belongsTo = array(
  'Post' => array(
    'className' => 'Post',
    'foreignKey' => 'post_id'
  ),
  'User' => array(
    'className' => 'User',
    'foreignKey' => 'user_id'
  )
);

PostController中

public function view($id = null) {
  //check it's valid, set the options to find the id
  $post = $this->Post->find('first', $options);
  //set the Post model, fire the view
}

然后在视图中我foreach$post['Comment']工作正常,但它不包含完整的用户模型,只包含Comment模型中的user_id键,它没有'追逐传递性。

我已尝试将recursive参数设置在find()一直到2,但这并未导致User模型下的Comment模型

更新:我正在查看我的帖子/查看操作的SQL日志,并且有2个不同的查询:

SELECT `Post`./*several fields*/, `User`./*several fields*/ FROM `blog`.`posts` AS `Post` LEFT JOIN `blog`.`users` AS `User` ON (`Post`.`user_id` = `User`.`id`) WHERE `Post`.`id` = 1 LIMIT 1  1   1   0   

SELECT `Comment`.`id`, `Comment`.`post_id`, `Comment`.`user_id`, `Comment`.`subject`, `Comment`.`body`, `Comment`.`created`, `Comment`.`previous_edit` FROM `blog`.`comments` AS `Comment` WHERE `Comment`.`post_id` = (1)

所以第一个查询是针对帖子的,它会进行连接以获取belongsTo关系。但是当它写入评论查询时,它只是在post_id上过滤而不加入users表。

1 个答案:

答案 0 :(得分:0)

我终于找到了它。我不得不使用hasMany关系的finderQuery属性。所以代码看起来像这样:

public $hasMany = array(
'Comment' => array(
  'className' => 'Comment',
  'finderQuery' => 'SELECT `Comment`./*several fields*/, `User`.`username` 
     FROM `blog`.`comments` AS `Comment` LEFT JOIN `blog`.`users` AS `User` ON
     (`Comment`.`user_id` = `User`.`id`) WHERE `Comment`.`post_id` = {$__cakeID__$}'
)

);

{$__cakeID__$}是一些蛋糕魔法,代表你正在处理的对象的id,在这个例子中是博客文章。