2016-09-15 77 views
1

我已經在model/entity/Order.php中實現了虛擬字段。如何訪問控制器中的虛擬字段而不是cakephp中的模型實體3.2

但我只想訪問一個頁面,我不希望它被調用所有的功能。因此,在控制器中,我如何訪問虛擬域,以便它只適用於我需要的部分。

在cakephp 2x版本中,我爲控制器製作了,但是這次是在3X中,我無法制作它。

下面我附上一些代碼

任何建議將不勝感激。 謝謝。在控制器

型號/實體/ Order.php

protected $_virtual = ['amount']; 

    protected function _getAmount() { 


      $data = []; 
      $data['due'] = $this->_properties['collection']['due_amount']; 
      $data['paid'] = $this->_properties['collection']['total_sale_amount'] - $this->_properties['collection']['due_amount']; 
      return $data; 
     } 

代碼

$Lists = $this->Orders->find('all')->where($condition)->contain(['Collections','Customers'=> ['queryBuilder' => function ($q) { 
           return $q->select(['id','center_name']); 
           }],])->order(['Orders.due_date ASC']); 

回答

2

您已通過聲明函數_get*使用實體的getter方法。你的getter方法名是_getAmount(),所以你可以通過控制器$ entity-> amount()中的實體對象來訪問它。

$Lists = $this->Orders->find('all')->where($condition)->contain(['Collections','Customers'=> ['queryBuilder' => function ($q) { 
           return $q->select(['id','center_name']); 
           }],])->order(['Orders.due_date ASC']); 

// Iteration will execute the query. 
foreach ($Lists as $entity) { 
     echo $entity->amount; 
} 

檢查文件有關virtual field in CakePHP 3.x

也沒必要在實體下方線,因此將其刪除,因爲你使用的getter方法。

protected $_virtual = ['amount']; 
+0

好吧,我會盡力。謝謝。 – sradha

+0

但它拋出一些錯誤,如Error:調用未定義的方法App \ Model \ Entity \ Order :: amount() – sradha

+0

你可以在foreach循環中調試($ entity)它有哪種類型的對象? –

相關問題