0

我有一个类似博客系统的东西。每个条目都可以有评论。每个评论都是由用户创建的。

我目前正在控制器上的“查看”操作中使用读取功能来检索所有数据。

模型之间的关系已经创建(belongTo、hasMany ...等)

当调用入口视图时,我得到如下信息:

['Entry'] => Array
    (
        [id] => 1
        [body] => 'xxxxxx'
        [...] => ...
    )

[Comment] => Array
    (
        [0] => Array
            (
                [id] => 1
                [user_id] => 1
                [body] => This is an example of a comment guys!
                [created] => 0000-00-00 00:00:00
            )

        [1] => Array
            (
                [id] => 2
                [user_id] => 1
                [body] => This is the 2nd comment!!!
                [created] => 0000-00-00 00:00:00
            )
    )

有没有办法通过读取功能来检索评论的“递归”数据,例如与 user_id 相关的用户数据?(为了得到他们的名字等)

我期待这样的事情:

['Entry'] => Array
    (
        [id] => 1
        [body] => xxxxxx
        [...] => ...
    )

[Comment] => Array
    (
        [0] => Array
            (
              [Comment] => Array
                   (
                      [id] => 1
                      [user_id] => 1
                      [body] => This is an example of a comment guys!
                      [created] => 0000-00-00 00:00:00  
                   )

              [User] => Array
                   (
                      [id] => 1
                      [username] => myusername
                      [created] => 0000-00-00 00:00:00  
                   )
            )

        [1] => Array
            (
              [Comment] => Array
                   (
                      [id] => 1
                      [user_id] => 2
                      [body] => fasdfasfaT
                      [created] => 0000-00-00 00:00:00  
                   )

              [User] => Array
                   (
                      [id] => 2
                      [username] => myusername2
                      [created] => 0000-00-00 00:00:00  
                   )
            )
    )

谢谢。

4

1 回答 1

1

是的。

您可以通过属性控制关联的深度recursive,或者使用containable行为来准确指定要包含的模型。AppModel.php我总是为( $actsAs = array('Containable');)中的所有模型启用此行为。然后像这样使用它:

$this->Entry->find('all', array(
    ...
    'contain' => array('Comment' => 'User')
));

结果将如下所示:

['Entry'] => Array
(
    [id] => 1
    [body] => xxxxxx
    [...] => ...
)

[Comment] => Array
(
    [0] => Array
        (
          [id] => 1
          [user_id] => 1
          [body] => This is an example of a comment guys!
          [created] => 0000-00-00 00:00:00  
          [User] => Array
               (
                  [id] => 1
                  [username] => myusername
                  [created] => 0000-00-00 00:00:00  
               )
        )

)

以我的经验,Cake 查询深度关联的效率不是很高。在您的情况下,它将为每个生成一个查询Comment以获取其User. 我会通过让 Cake 只获取评论来避免它,然后提取评论的用户 ID,在一个查询中获取所有具有这些 ID 的用户,然后将该用户信息添加到原始结果中。

于 2012-09-24T09:10:38.867 回答