我有两个模型,分别是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
知道它被Batch
称为Customer
,因此自动读取模型中Batch
关联的正确条件?
我想让我的代码更具可读性,因此这个问题的动机。
我想简单地写
$customers = $this->Batch->Customer->find('list');
或类似简单的东西。
当然,我意识到如果我执行以下操作:
$batches = $this->Batch->find('all');
将使用关联中规定的条件。但我不想找到批次。我只想找到客户。
我正在使用 CakePHP 2.4
我认为你不能
但您可以在模型文件中创建自定义查找类型 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(
什么都不做。
继续使用类似代码
$customers = $this->Batch->Customer->find('list', array('conditions' => array('Customer.group_id' => CUSTOMERS)));
2(
按照 Ailia 的建议创建自定义查找方法。
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');
更新:
我编写了一个插件来帮助解决这种行为,利用第三种解决方案。
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');
此行为在 travis 有测试,您可以阅读有关在 github 上编写的测试的信息。