Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/jsf/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Cakephp 在蛋糕2中相同的条件集上运行find(';all';)或find(';first';)_Cakephp - Fatal编程技术网

Cakephp 在蛋糕2中相同的条件集上运行find(';all';)或find(';first';)

Cakephp 在蛋糕2中相同的条件集上运行find(';all';)或find(';first';),cakephp,Cakephp,在我的CakePHP2应用程序中的controller/index操作中,我有 $this->Model-find('all',array( ... lots conditions and things... )); 然后,在controller/view中,我有: $this->Model-find('first',array( ... lots conditions and things... )); 这两种方法都非常有效,但我显然在重复大量代码(即查找条件、字段列表等),只

在我的CakePHP2应用程序中的
controller/index
操作中,我有

$this->Model-find('all',array( ... lots conditions and things... ));
然后,在
controller/view
中,我有:

$this->Model-find('first',array( ... lots conditions and things... ));
这两种方法都非常有效,但我显然在重复大量代码(即查找条件、字段列表等),只有两个区别,第一个是我在执行
find('all')
,第二个是我在执行
find('first')
,并将id作为条件之一


是否有一种方法可以将条件移动到模型中,然后对这些条件运行不同类型的查找?

是的,您可以将查询作为函数/方法移动到模型类中。有关立柱模型,请参见下面的示例:

class Post extends AppModel {
    public $name = 'Post';

    public function getAll() {
       return $this->find('all', array('limit' => 20, 'order' => 'Post.created DESC'));
    }
}
并通过$this->Model->getAll()在控制器上调用它


您还可以向函数中添加参数。

您可以在您的模型中创建一个方法:

public function getConditions($id = null) {
   return array( ... lots conditions and things... );
}
在这个方法的某个地方,只需测试
(!empty($id))
是否返回正确的结果。(您没有提供“条件和事项”,因此我无法在此处编写确切的代码

并在两种控制器操作中使用它:

$this->Model->find('first', $this->Model->getConditions()));

$this->Model->find('all', $this->Model->getConditions()));

将条件添加为控制器的属性

class FoosController extends AppController{

    public $conditions = array( ... lots conditions and things... )

    public function index(){
        $this-Foo->find('all', $this->conditions);
    }

    public function view(){
        $this-Foo->find('first', $this->conditions);
    }
}
class FoosController extends AppController{

    public $conditions = array( ... lots conditions and things... )

    public function index(){
        $this-Foo->find('all', $this->conditions);
    }

    public function view(){
        $this-Foo->find('first', $this->conditions);
    }
}