鑑於

2013-11-26 101 views
0

使用功能從模型在CakePHP我有看起來像這樣的模型客戶:鑑於

<?php 

class Customer extends AppModel { 
    public $hasMany = array(
     'Invoice' => array(
      'className' => 'Invoice', 
     ) 
    ); 

    public function getDisplayName($id){ 
     $customer = new Customer(); 
     $customer_array = $customer->find('first', array(
      'conditions' => array('Customer.id' => $id) 
     )); 

     if($customer_array['Customer']['company']){ 
      return $customer_array['Customer']['company']; 
     } else { 
      return $customer_array['Customer']['frontname'] . ' ' . $customer_array['Customer']['lastname']; 
     } 
    } 

    public function getFullName($id){ 
     $customer = new Customer(); 
     $customer_array = $customer->find('first', array(
      'conditions' => array('Customer.id' => $id) 
     )); 

     return $customer_array['Customer']['frontname'] . ' ' . $customer_array['Customer']['lastname']; 
    } 

} 
?> 

在其他視圖(項目),我想告訴客戶有顯示名稱的列表(因爲其中一些有一家公司,其他公司則沒有)。

所以在ProjectController我加了這一點:

$customers = $this->Project->Customer->find('list', array(
    'fields' =>array(
     'Customer.id', $this->Project->Customer->getDisplayName('Customer.id') 
    ), 
    'conditions' => array(
     'Customer.cloud_id' => '1' 
    ) 
));    
$this->set('customers', $customers); 

但後來我得到一個MySQL的錯誤,因爲第二個字段不是databasecolumn。

誰能幫我解決這個問題?

回答

1

你最好的最好的將是您的客戶模型中使用的虛擬域: 請參閱該文檔:http://book.cakephp.org/2.0/en/models/virtual-fields.html在項目控制器

<?php 
class Customer extends AppModel { 
    public $hasMany = array(
     'Invoice' => array(
      'className' => 'Invoice', 
     ) 
    ); 
    public $virtualFields = array(
     'display_name' => 'IF(Customer.company IS NOT NULL, Customer.company, CONCAT_WS(' ', Customer.frontname, Customer.lastname))' 
    ); 
} 
?> 

然後:

<?php 
$customers = $this->Project->Customer->find('list', array(
    'fields' =>array(
     'Customer.id', 'Customer.display_name' 
    ), 
    'conditions' => array(
     'Customer.cloud_id' => '1' 
    ) 
));    
$this->set('customers', $customers); 
?> 
0

要更普遍回答這個問題(在這裏虛擬字段解決方案工作正常),您可以重寫getDisplayName函數並將其放入Controller中。

然後,你可以使用

$displayName= $this->requestAction(array(
    'controller'=>'CustomersController', 
    'action'=>'getDisplayName ') 
); 

echo $displayName; 
認爲叫它