CakePHP - 只有一个来自外部模型的查询

时间:2012-04-01 21:38:55

标签: php cakephp model

我有两个模特:

class Post extends AppModel {
    var $name = 'Post';
    var $belongsTo = array(
        'User' => array(
            'className' => 'User', 
            'foreignKey' => 'user_id'
        )
    );      
}

class User extends AppModel {
    var $name = 'User';
    var $hasMany = 'Post';
}

现在我遇到PostsController中的查询问题。我有一个add()函数和视图add.ctp,它基本上是一个表单。现在我想以该表单显示一些用户信息。

class PostsController extends AppController {
    var $name = 'Posts';
    var $helper = array('Html', 'Form');
    var $uses = array('User');

    public function index() {
        $this->set('posts', $this->Post->find('all'));
    }

    function add() {
        $user_id = 1;
        $this->set('user', $this->User->findById($user_id));
        if ($this->request->is('post')) {
            if ($this->Post->save($this->request->data)) {
                $this->Session->setFlash('Your post has been saved.');
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash('Unable to add your post.');
            }
        }
    }
}

但是现在add-view-page显示实际上两个查询被触发了。因此,如果我在添加视图中print_r($user),我将获得一个包含两个数组的数组。一个用于具有user_id = 1的帖子,一个用于具有id = 1的实际用户。但是我想仅获得用户id = 1。

1 个答案:

答案 0 :(得分:2)

在调用recursive之前,请尝试在false模型上将User设置为findById,这样您就无法从相关模型中获取任何数据。像这样:

function add() {
    $user_id = 1;
    $this->User->recursive = false;
    $this->set('user', $this->User->findById($user_id));
    if ($this->request->is('post')) {
        if ($this->Post->save($this->request->data)) {
            $this->Session->setFlash('Your post has been saved.');
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash('Unable to add your post.');
        }
    }
}