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();
        },
    ],
    ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备