协会:HasMany里面有一个BelogsTo

时间:2015-10-23 15:36:02

标签: cakephp cakephp-2.5

您好我正在尝试使用CakePHP 2.5并从教程中创建博客。 我正在为博客帖子添加评论,每个评论都有一个用户,但我似乎无法撤回用户信息。

在我的用户模型中

public $hasMany = array(
    'Comment' => array(
        'className' => 'Comment',
        'foreignKey' => 'user_id',
        'dependent' => false,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => ''
    ),
    'Post' => array(
        'className' => 'Post',
        'foreignKey' => 'user_id',
        'dependent' => false,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => ''
    )
);

在我的评论模型中

public $belongsTo = [
    'User' => [
        'className' => 'User',
        'foreignKey' => 'user_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    ],
    'Posts' => [
        'className' => 'Posts',
        'foreignKey' => 'post_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    ]
];

并且在postmodel中,post is whenre我想显示评论和用户名

public $belongsTo = [
    'User' => [
        'className' => 'User',
        'foreignKey' => 'user_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    ]
];

public $hasMany = [
    'Comment' => [
        'className' => 'Comment',
        'order'     => 'Comment.created DESC',
        'foreignKey'=> 'post_id'
    ]
];

查看帖子会带回以下评论信息

  'Comment' => 
    array (size=1)
      0 => 
        array (size=6)
          'id' => string '1' (length=1)
          'content' => string 'This is a comment' (length=17)
          'created' => string '2015-10-23 15:59:55' (length=19)
          'modified' => string '2015-10-23 15:59:55' (length=19)
          'user_id' => string '1' (length=1)
          'post_id' => string '2' (length=1)

但这不包括我预期的用户信息。

我的问题是如何为帖子中的每条评论提取用户信息

1 个答案:

答案 0 :(得分:1)

对不起,我没有评论要点。你可以发布你的find()方法吗?此外,你是否开启了递归,或者它已关闭(转为-1)并且你使用包含来获取相关模型?