使用CakePHP中的read方法加载其他模型数据

时间:2012-09-26 14:23:34

标签: php cakephp

我在编辑方法中有以下代码,允许用户编辑其帐户详细信息。它使用User和Profile模型,并且应该更新它们。

我已经使用find中的contains来加载Profile信息,并使用控制器顶部的$ uses var来调用Profile模型。

但是如何将两个模型加载到read方法中?

$user = $this->User->find('first', array( 
                    'conditions' => array('User.id' => $this->Auth->user('id')),
                    'contain'=>'Profile'
                ));

        if ($this->request->is('post') || $this->request->is('put'))
        {
            if ($this->User->save($this->request->data))
            {
                $this->Session->setFlash(__('Your account has been saved'));
                $this->redirect(array('controller'=>'users','action'=>'edit'));
            }
            else
            {
                $this->Session->setFlash(__('Whoops! Something went wrong... try again?'));
            }
        }
        else
        {
            $this->request->data = $this->User->read(null, $user['User']['id']);
        }

3 个答案:

答案 0 :(得分:1)

据我所知,文档read()只能带来预期的字段。如果您想阅读相关模型,请改用find

而不是:

$this->request->data = $this->User->read(null, $user['User']['id']);

使用它:

$this->request->data = $this->User->find('all', 
       array(
         'conditions' => array('User.id' => $user['User']['id']), 
         'contain'    => 'Profile'
       )
);

http://book.cakephp.org/1.3/en/view/1018/find

答案 1 :(得分:0)

您可以在read()之前调用contains()方法。

$this->User->contain(array('Profile'));
$this->request->data = $this->User->read(null, $user['User']['id']);

请注意,在调用find()的read()之后,此调用contains()的效果将不会持续。

答案 2 :(得分:0)

刚做完:$this->request->data = $user;

似乎工作正常。任何人都可以通过这种方式看到任何问题吗?