鉴于

2013-11-26 41 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; 
认为叫它