我有两个名为Batch
和User
Batch
有以下
public $belongsTo = array(
'Customer' => array(
'className' => 'User',
'foreignKey' => 'customer_id',
'conditions' => array('Customer.group_id' => CUSTOMERS),
'fields' => '',
'order' => '',
),
);
当我执行以下操作时:
$customers = $this->Batch->Customer->find('list');
我完全希望只返回group_id
匹配CUSTOMERS
的用户。它返回users
表中的所有记录。
然而,我实际上必须写
$customers = $this->Batch->Customer->find('list', array('conditions' => array('Customer.group_id' => CUSTOMERS)));
是否有一种方法可以使链式模型User
知道它被Customer
称为Batch
,因此会自动读取Batch
中找到的关联中的正确条件模特?
我想让我的代码更具可读性,因此这个问题的动机。
我想写简单
$customers = $this->Batch->Customer->find('list');
或类似的直截了当。
当然,我意识到如果我做以下事情:
$batches = $this->Batch->find('all');
将使用协会中陈述的条件。但我不想找到批次。我想找到客户。
我正在使用CakePHP 2.4
答案 0 :(得分:1)
我认为你不能
但您可以在User
模型文件
public $findMethods = array('customer' => true); //this enable a custom find method named 'customer'
protected function _findCustomer($state, $query, $results = array()) {
if ($state === 'before') {
$query['conditions'] = array('group_id' => CUSTOMERS);
}
return parent::_findList($state, $query, $results);
}
并在BatchesController
$this->Batch->Customer->find('customer');
答案 1 :(得分:0)
有几种方法可以做到这一点。
1)
什么都不做。
继续使用
之类的代码$customers = $this->Batch->Customer->find('list', array('conditions' => array('Customer.group_id' => CUSTOMERS)));
2)
create a custom find method as suggested by arilia
3)
在getCustomers
模型
Batch
方法
它看起来像这样:
public function getCustomers($type, $query = array()) {
if (empty($query['conditions'])) {
$query['conditions'] = array();
}
$query['conditions'] = array_merge($query['conditions'], array('Customer.group_id' => CUSTOMERS));
return $this->Customer->find($type, $query);
}
然后你可以打电话
$customers = $this->Batch->getCustomers('list');
<强>更新强>
我已经写了一个Plugin来帮助解决这种行为,利用第三种解决方案。
class Batch extends AppModel {
public $name = 'Batch';
public $actsAs = array('UtilityBehaviors.GetAssoc');
public $belongsTo = array(
'Customer' => array(
'className' => 'User',
'foreignKey' => 'customer_id',
'conditions' => array('Customer.group_id' => 7),
'fields' => '',
'order' => '',
),
);
}
当您使用BatchesController时,您可以只获取客户数据:
$customers = $this->Batch->getAssoc('Customer', 'list');
$customers = $this->Batch->getAssoc('Customer', 'all');
$customerCount = $this->Batch->getAssoc('Customer', 'count');