簡體   English   中英

如何訪問控制器中的虛擬字段而不是cakephp 3.2中的模型實體

[英]How to access virtual field in controller instead of model entity in cakephp 3.2

我已經在model / entity / Order.php中實現了虛擬歸檔。

但是我只想訪問一頁,我不希望所有功能都調用它。所以在控制器中我如何訪問虛擬字段,以便它僅適用於我需要的部分。

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

您已經通過聲明函數_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;
}

在CakePHP 3.x中檢查有關虛擬字段的文檔

另外,不需要在Entity中的下一行,因此將其刪除,因為您正在使用getter方法。

protected $_virtual = ['amount'];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM