Cakephp包含更深层次的关联

时间:2016-07-24 14:35:58

标签: cakephp cakephp-2.0

我正在拥有一个用户可以喜欢的博客并对其进行评论。对于Blog View操作,我将列出此博客条目的所有评论。直到现在我能够列出所有评论,但我也想显示用户名,不幸的是我只在评论对象中获得了User_id。我该怎么办?我已经尝试了recursive = 2.

Here is a trace of the variable:

它给出了一个错误Model" Rmcomment"与模型" User"无关。 [APP / Vendor / cakephp / cakephp / lib / Cake / Model / Behavior / ContainableBehavior.php,第342行]虽然只有查询的最后一级不起作用

1 个答案:

答案 0 :(得分:0)

埃洛,伙计。尝试在查找查询中使用 join

$this->Rmcomment->find('all', array(
 'joins' => array(
      array(
      'table' => {{ya users table name}},
      'alias' => 'User',
      'type' => 'LEFT',
      'conditions' => array('User.id = Rmcomment.user_id')
   ),
  'fields' => array(
    'Rmcomment.something', 
    'Rmcomment.somethingelse', 
    'User.name' //Here comes your name from users table using the user_id from comments
    ),
  'group' => 'Rmcomment.id'
  )
 )
);

它应该返回:

array(
    array(
        'Rmcomment' => array(
            '!fields from Rmcomment!'
        ),
        'User' => array(
            '!fields from User!'
        )
    ),
    array(
         'Rmcomment' => array(
            '!fields from Rmcomment!'
        ),
        'User' => array(
            '!fields from User!'
        )
     ).........
 );