在CakePHP 2.0中访问控制器内的模型数据

时间:2012-01-26 23:52:18

标签: php cakephp

我正在尝试使用我的模型中的控制器方法访问数据。

对于初学者来说,这两者之间有什么区别?

$post = $this->Post->find('first',array('conditions'=>array('Post.id'=>$id)));

$this->set(compact('post'));

$this->Post->id = $id;

$this->data = $this->Post->read();

因为我正在尝试将帖子的user_id与登录用户进行比较,如下所示:

if($this->Post->user_id != $this->Auth->user('id'))

但是它没有按预期工作(它总是返回false)...两个代码块之间有什么区别?为什么我的上面的行不能正常工作?

3 个答案:

答案 0 :(得分:1)

测试以查看是否有助于比较此代码“userid”:

function index() {

   $user_id = $this->data['Post']['user_id'];
   if($user_id != $this->Auth->user('id')){
    //go
   }

}

答案 1 :(得分:1)

这就是我最终的结果:

$post = $this->Post->find('first',array('conditions'=>array('Post.id'=>Tiny::reverseTiny($id))));

        if ($this->request->is('post') || $this->request->is('put'))
        {
            $this->Post->id = $post['Post']['id'];
            if ($this->Post->save($this->request->data))
            {
                $this->Session->setFlash('Your post has been updated');
                $this->redirect(array('controller' => 'posts', 'action' => 'index'));
            }
            else
            {
                $this->Session->setFlash('Server broke!');
            }
        }
        else 
        {
            if($post['Post']['user_id'] != $this->Auth->user('id'))
            {
                $this->Session->setFlash('Not yours!');
                $this->redirect(array('controller' => 'posts', 'action' => 'index'));
            }
            else
            {               
                $this->request->data = $this->Post->read(null, $post['Post']['id']);
            }
        }

答案 2 :(得分:0)

find()read()之间存在差异,读取将获取所有相关模型数据并将模型的活动记录设置为结果。而查找将只查询查询中的所有相关模型数据,并将结果分配给变量。

使用debug($this->data)显示返回数据的结构。您会发现用户ID为$this->data['Post']['user_id']

相关问题