Yii2 Gridview:如何一次调用模型函数,但是在多列中使用它的结果?

时间:2017-05-02 16:14:59

标签: php gridview yii2

在模型中我有功能:

public function getResult($id)
{
    $result = new \stdClass();
    $result->alfa = $id.10;
    $result->beta = $id.20;
    $result->delta = $id.50;
    return $result;
}

在网格视图中,我只想调用此函数一次,但在单独的列中显示每个值。现在视图看起来像这样:

[
    ...
    [
        'value' => function($item){
            $res = $item->result();
            return $res->alfa;
        },
    ],
    [
        'value' => function($item){
            $res = $item->result();
            return $res->beta;
        },
    ],
    [
        'value' => function($item){
            $res = $item->result();
            return $res->delta;
        },
    ],
    ...
]

我已经读过,没有办法将值从一列传递到另一列,但它应该是一些解决方法,对吧?到目前为止,我已尝试在列之前获取值,然后将其添加为:function($ item)use($ result){},也称为搜索模型中的函数,但我不能(或者只是不知道)如何)将值传递给他们。

在'真实'模型中,我得到了请求值 - 没有办法将它拆分,而且,那些计算非常复杂,所以我需要摆脱那些多次调用,因为你可以想象加载时间是讨厌的那些额外的电话

感谢您提供任何有用的信息或想法!

1 个答案:

答案 0 :(得分:1)

非常感谢您的建议,这真的很有帮助!这就是我最终做的事情:

<强>模型

private $_alfa, $_beta, $_delta;

public function getAlfa()
{
    return $this->_alfa;
}

public function getBeta()
{
    return $this->_beta;
}

public function getDelta()
{
    return $this->_delta;
}

public function getResult($id)
{
    $this->_alfa = $id.10;
    $this->_beta = $id.20;
    $this->_delta = $id.50;
}

查看

...
[
    'value' => function($item){
        $item->getResult($item->id);
        return $item->getAlfa();
    },
],
[
    'value' => function($item){
        return $item->getBeta();
    },
],
[
    'value' => function($item){
        return $item->getDelta();
    },
],
...