关联:HasMany,里面有一个 BelogsTo

Associations: HasMany with a BelogsTo inside it

您好,我正在试用 CakePHP 2.5 并根据教程创建了博客。 我正在给博客posts添加评论,每条评论都有一个用户,但我似乎无法撤回用户信息。

在我的用户模型中

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' => ''
    ]
];

并且在 post 模型中,post 当我想显示评论和用户名时

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

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

查看一条post带回以下评论信息

  '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)

但这并没有像我预期的那样包含用户信息。

我的问题是如何提取 post

中每个评论的用户信息

抱歉,我没有积分可以评论。你能 post 你的 find() 方法吗?另外,你是否打开了递归,或者它是否关闭(变为 -1)并且你正在使用 contain 来获取关联模型?