代码之家  ›  专栏  ›  技术社区  ›  aiternal

如何在Cakephp中为多个sql查询使用一个控制器?

  •  1
  • aiternal  · 技术社区  · 16 年前

    我的索引页有4个不同的mysql查询。我试着在一个控制器和一个视图中编写这个代码。这条路不对。然后有人建议在requestAction()函数中使用4个元素。一开始很不错。然后我需要命令。我找不到它与requestAction()一起使用的方法。我关于Cakephp组的问题仍然没有答案。有人建议在控制器中使用动作。但我不知道如何创建那个控制器。

    请告诉我你知道些什么。提前谢谢,

    以下是我当前的post controller的索引函数:

    function index() {
            $posts = $this->paginate();
            if (isset($this->params['requested'])) {
                return $posts;
            } else {
                $sql = array( 'conditions' => array( 'id BETWEEN ? AND ?' => array( 286, 291 ) ) );
                $this->Post->find('all', $sql);
                $this->set('posts', $posts);
            }
    }
    

    1 回复  |  直到 16 年前
        1
  •  1
  •   bancer    16 年前

    每次需要在单个控制器中执行多个查询时,我都会这样做:

    // model Foo
    function edit($id){
        $this->data = $this->Foo->read(null, $id);
        $second = $this->Foo->Foo2->find('list');
        $third = $this->Foo->Foo3->find('list');
        $this->set(compact('second', 'third')); 
    }
    

    我猜,你想在这3列上分页,所以上面的例子不适合。

    我认为你的方法有错误。 $posts 与您的 find $posts = $this->Post->find('all', $sql); . 但这不允许您对结果分页。看一看 Custom Query Pagination

    function index(){
        if(!isset($this->params['requested'])) {
            $this->paginate = array('Post' => array(
                'conditions' => array('id BETWEEN ? AND ?' => array(286, 291))
            ));
        }
        $this->set('posts', $this->paginate());
    }