博客文章/评论/用户模型中的 CakePHP 传递关联


CakePHP transitive associations in the Blog Post/Comment/User Model

我正在自学蛋糕PHP,我有一个关于模型关联的问题。我正在添加一个评论系统。问题出在我的帖子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'
  )
);

后控制器

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,但这不会在Comment模型下引入User模型

更新:我正在查看我的帖子/视图操作的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)

因此,第一个查询是针对帖子的,它执行联接以选取归属关系。但是当它写入注释查询时,它只是在post_id上过滤,而不加入用户表。

我终于找到了。我不得不使用关系的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,在本例中为博客文章。