2013-10-10 33 views
0

我有兩個型號稱爲BatchUser如何讓鏈式模型自動讀取條件?

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

回答

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'); 

UPDATE:

我寫了一個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'); 

此行爲已經在travis測試,你可以看到在github編寫了測試。

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');