【问题标题】:CakePHP - Only one Query from external ModelCakePHP - 只有一个来自外部模型的查询
【发布时间】:2012-04-02 05:50:02
【问题描述】:

我有两个模型:

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。

【问题讨论】:

  • 您想从哪里获取 id 为 1 的用户?在PostsController::add()?
  • 抱歉,$user 是从视图中,我是对的?
  • 是的,$user 来自视图,我希望在我的视图中有一个 id = 1 的用户数组。

标签: php cakephp model


【解决方案1】:

在调用findById 之前,尝试在User 模型上将recursive 设置为false,这样您就不会从关联模型中获得任何数据。像这样:

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.');
        }
    }
}

【讨论】:

  • 谢谢!现在视图中只有 User 数组可用,但是当我现在保存 add-view 的 from 时.. 我收到一个致命错误:调用非对象上的成员函数 save() /home/app/Controller/PostssController.php 第 17 行。
  • 第 17 行是这个吗:$this->Post->save($this->request->data)?如果是,则说明找不到Post模型,很奇怪(应该是自动可用的)。但是您始终可以将其添加到控制器顶部的$uses 数组中。你的命名方案有一些奇怪的地方,可能是让蛋糕找不到模型:你的控制器文件真的叫PostssController.php,有两个s吗?
  • 这两个是刚刚发生的,因为我错误地重命名了那个错误中的文件。但是,当我将 Post 添加到 $uses 时,您的权利,由于某种原因,只有它才能工作并且数据被保存。正如您所说,Post 实际上应该已经在 PostsController 中可用。我不知道。
  • @JonasMillan,另一个可能的原因:如果在 cake 2.x 中文件未命名为 /app/Model/Post.php,cake 将找不到模型。
  • 好吧,由于某种原因,$uses 也需要传递它的实际模型。所以最后它对我来说很好 - 谢谢!
猜你喜欢
  • 2018-07-14
  • 2017-06-16
  • 2015-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-01
相关资源
最近更新 更多