我正在尝试使用新的 CakePHP 3.0,但在确定将查询放在何处时遇到了一些麻烦。
假设我们有这样的东西,直接来自他们的文档。
$articles = $this->Articles->find('all', [
'fields' => ['id', 'title'],
'conditions' => [
'OR' => ['title' => 'Cake', 'author_id' => 1],
'published' => true
],
'contain' => ['Authors'],
'order' => ['title' => 'DESC'],
'limit' => 10,
]);
我应该把这段代码放在哪里?在我的 Controller 类或模型文件夹中。
如果我需要将此代码放入我的 Controller 类中,并且将来我想重用此查询。我是否必须在另一个 Controller 中重写查询?
如果在模型文件夹中,我应该把它放在哪个文件夹中?行为、实体还是表?我将如何使用它?
谢谢
最佳答案
如果你只使用一次,你可以把它放在一个 Controller Action 中。但是我们喜欢我们的模型胖所以你应该把它放在你的模型(表)的一个方法中以实现可重用性(保留你的代码 DRY )
之后你就可以在你的 Controller 中使用这个方法了
$this->loadModel('Model'); //if needed
$this->Model->nameOfYourMethod();
关于php - CakePHP 3.0 在哪里放置查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31185429/