Cakephp 在蛋糕2中相同的条件集上运行find(';all';)或find(';first';)
在我的CakePHP2应用程序中的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... )); 这两种方法都非常有效,但我显然在重复大量代码(即查找条件、字段列表等),只
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);
}
}