我一直在努力学习更多关于如何有脂肪模型和瘦控制器的正确方式,因为之前我的模型基本上没有代码,我试图改变这一点。我的函数工作,但现在我试图结合两个find()查询,看起来几乎完全相同,除了其中一个有一个简单的条件。
我的模型看起来像这样:
function pieChart() {
//Get Data for PieChart
$this->RecordDrug->virtualFields['sum'] ='COUNT(*)';
$records = array();
$records=$this->RecordDrug->find('list',
array('fields' => array( 'Drug.drug', 'sum'),
'contain' => array( 'Drug', 'Record' ),
'group' => 'Drug.Drug'
));
$this->set('output',$records);
return $records;
}
I will have two controllers using this. One of them will use this code as is, just simply call the pieChart() function. The other controller will have to see a condition that only selects the users entries. So
'conditions' => array('Record.user_id' => $this->Auth->user('id'))
我该怎么做才对呢?我想我遇到了麻烦,因为我的面向对象的知识是相当有限的。如果有人有任何例子或资源,可以帮助我使我的find()函数更有效和精简,我真的很感激。
我做的事情很简单:
public function myQuery($conditions = null) {
$this->virtualFields['sum'] ='COUNT(*)';
$result = $this->find('all', array('conditions' => $conditions,
'fields' => array('Drug.drug', 'sum'),
'contain' => array('Drug','Record'),
'group' => 'Drug.Drug'
));
return $result;
}
现在你可以用你的参数来调用它:
$conditions = array('Record.user_id' => $this->Auth->user('id'));
$data = $this->RecordDrug->myQuery($conditions);
或者没有
$data = $this->RecordDrug->myQuery();
注意,在这种情况下,您需要将myQuery()
放入RecordDrug模型,并且您需要使用'all'
而不是'list'
,因为'list'
不支持contain
选项。
那么现在如果你有额外的条件-你只需要在参数中传递它。