Php 在视图中使用模型中的函数

Php 在视图中使用模型中的函数,php,cakephp,cakephp-model,Php,Cakephp,Cakephp Model,在CakePHP中,我有一个模型客户,如下所示: <?php class Customer extends AppModel { public $hasMany = array( 'Invoice' => array( 'className' => 'Invoice', ) ); public function getDisplayName($id){ $customer = n

在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'];
    }

}
?>
但是我得到了一个MySQL错误,因为第二个字段不是databasecolumn


谁能帮我回答这个问题?

您最好在客户模型中使用虚拟字段: 见文件:


然后在项目控制器中:

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

要更笼统地回答这个问题(这里虚拟字段解决方案工作正常),您可以重写getDisplayName函数并将其放入控制器中

然后您可以使用

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

echo $displayName;
<?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);
?>
$displayName= $this->requestAction(array(
  'controller'=>'CustomersController',
  'action'=>'getDisplayName ')
);

echo $displayName;