doudiza9154 2012-04-01 21:38
浏览 25
已采纳

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

I've two Models:

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

and

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

Now I'm having a problem with a query in the PostsController. I've an add() function and the view add.ctp which is basically a form. Now I would like to show some User information in that form.

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

But now the add-view-page shows that actually two queries where triggered. So if I print_r($user) within the add-view I'm getting an array with two arrays. One for a Post with user_id = 1 and one for the actual User with id = 1. But I would like to get only the User id = 1.

  • 写回答

1条回答 默认 最新

  • dqp21271 2012-04-01 21:50
    关注

    Try setting recursive to false on the User model before calling findById, so you won't get any data from associated models. Like this:

    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.');
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛