簡體   English   中英

Yii2 Gridview:如何一次調用模型函數,但是在多列中使用它的結果?

[英]Yii2 Gridview: how to call model function one time, but use it's results in multiple columns?

在模型中,我有功能:

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){},也稱為搜索模型中的function,但是我做不到(或只是不知道如何)將值傳遞給他們。

在“真實”模型中,我通過請求獲取值-無法拆分它,而且這些計算非常復雜,因此我需要擺脫這些多次調用,因為您可以想象,加載這些額外的內容會很麻煩來電

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

非常感謝您的建議,它真的很有幫助! 這就是我最終要做的事情:

模型

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();
    },
],
...

暫無
暫無

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

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