doutuo7609 2017-05-02 16:14
浏览 52
已采纳

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

In model I have function:

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

In grid view I'd like to call this function ONLY ONE time, but display each value in separate column. Now view looks like that:

[
    ...
    [
        '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;
        },
    ],
    ...
]

I've read, that there is no way to pass value from one column to another, but it should be some work around, right? So far I've tried to get values before columns and then add it like that: function($item) use ($result) {}, also called function from search model, but I can't (or just don't know how) pass values to them.

In 'real' model I get values with request - there is no way to split it, also, those calculations are quite complex, so I need to get rid of those multiple calls, because as you can imagine loading time is nasty with those extra calls

Thanks for any helpful info or ideas!

  • 写回答

1条回答 默认 最新

  • doumeng3188 2017-05-02 21:03
    关注

    Thank you so much for suggestions, it really helped! This is what I ended up doing:

    Model

    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;
    }
    

    View

    ...
    [
        'value' => function($item){
            $item->getResult($item->id);
            return $item->getAlfa();
        },
    ],
    [
        'value' => function($item){
            return $item->getBeta();
        },
    ],
    [
        'value' => function($item){
            return $item->getDelta();
        },
    ],
    ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 Keil uVision5创建project没反应
  • ¥15 mmseqs内存报错
  • ¥15 vika文档如何与obsidian同步
  • ¥15 华为手机相册里面的照片能够替换成自己想要的照片吗?
  • ¥15 陆空双模式无人机飞控设置
  • ¥15 sentaurus lithography
  • ¥100 求抖音ck号 或者提ck教程
  • ¥15 关于#linux#的问题:子进程1等待子进程A、B退出后退出(语言-c语言)
  • ¥20 web页面如何打开Outlook 365的全球离线通讯簿功能
  • ¥15 io.jsonwebtoken.security.Keys