CakePHP-在模型中查找没有hasMany关系的hasMany关联?

CakePHP-在模型中查找没有hasMany关系的hasMany关联?,php,cakephp,has-many,Php,Cakephp,Has Many,再次,我想问你一个关于CakePHP的问题:我有两个模型用户和注释,关系为1-n(一个用户有许多注释)。我想使用find()列出用户及其评论的信息,格式数据返回: Array ( [User] => Array ( [id] => 121 [name] => Gwoo the Kungwoo [created] => 2007-05-01 10:31:01 )

再次,我想问你一个关于CakePHP的问题:我有两个模型用户和注释,关系为1-n(一个用户有许多注释)。我想使用find()列出用户及其评论的信息,格式数据返回:

Array
(
    [User] => Array
        (
            [id] => 121
            [name] => Gwoo the Kungwoo
            [created] => 2007-05-01 10:31:01
        )
    [Comment] => Array
        (
            [0] => Array
                (
                    [id] => 123
                    [user_id] => 121
                    [title] => On Gwoo the Kungwoo
                    [body] => The Kungwooness is not so Gwooish
                    [created] => 2006-05-01 10:31:01
                )
            [1] => Array
                (
                    [id] => 124
                    [user_id] => 121
                    [title] => More on Gwoo
                    [body] => But what of the 'Nut?
                    [created] => 2006-05-01 10:41:01
                )
        )
)
但我不想将关系在模型用户中配置为链接中的示例:。我尝试了以下代码:

 $data = $this->User->find('all', array(
                'joins' => array(
                    array(
                        'table' => 'comment',
                        'alias' => 'Comment',
                        'type' => 'LEFT',
                        'conditions' => array(
                            'User.id = Comment.user_id'
                        )
                    ),
                    'conditions' => array(
                       'User.id' => $userId
                    ),
                     'fields' => array('User.*', 'Comment.*')
            ));
并返回一个包含重复用户记录的数组(例如:如果用户有2条注释,则返回2条重复用户记录)


有人能给我另一个解决办法吗?(除了配置有许多关系模型的解决方案外),谢谢。

或者,您可以在控制器中使用bindModel

        $this->User->bindModel(
               array(
                 'hasMany'=>array(
                     'Comment' =>array(
                      'className' => 'Comment',
                      'foreignKey' => 'user_id',
                      'conditions' => array('Comment.status' => 'Active'),
                  )         
               )
            )
        ); 

        $data = $this->User->find('all',array('conditions'=>array('User.email'=>$userEmail)));
更多

已更新


查看此部分了解一些信息,通过此查看有关绑定和解除绑定模型的详细信息

请检查此部分:-当这是您的基本情况时,您不定义hasMany关系的理由是什么?非常感谢!您节省了我的时间:)但是如果我使用bindModel(),我是否使用unbindModel()删除关联?是的,如果您不需要不必要的数据。