【问题标题】:How to access virtual field in controller instead of model entity in cakephp 3.2如何在 cakephp 3.2 中访问控制器中的虚拟字段而不是模型实体
【发布时间】:2017-01-23 05:53:11
【问题描述】:

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

【问题讨论】:

    标签: php cakephp cakephp-3.x cakephp-3.2


    【解决方案1】:

    您通过声明函数_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的文档

    Entity中也不需要下面一行,所以删除它,因为你使用的是getter方法。

    protected $_virtual = ['amount'];
    

    【讨论】:

    • 但它会抛出一些错误,例如 Error: Call to undefined method App\Model\Entity\Order::amount()
    • 你能在foreach循环中调试($entity)它有什么类型的对象吗?
    • 好的。我会
    • 哦.. 使用$entity->amount 而不是$entity->amount()
    • 是的,我知道了,但还有一个问题,如何将它放在一个数组中。我的意思是结果应该单独与主数组合并。这样我就可以轻松访问。
    猜你喜欢
    • 1970-01-01
    • 2021-07-08
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多