Has_many relation in DetailView

这一生的挚爱 提交于 2019-12-11 03:54:55

问题


I have the following code in use in gridview and it's working perfectly:

                    ['format' => 'raw',
                'label' => 'Categories',
                'value' => function ($data) {
                    $string = '';
                    foreach ($data['fkCategory'] as $cat) {
                        $string .= $cat->category_name . '<br/>';
                    }
                    return $string;
                }],

This displays all the item's categories on new row within the table cell. However if I want to display something similar in DetailView, it's not working. Detailview gives me an error:

Object of class Closure could not be converted to string

So how is it possible to access has_many relations in DetailView?

The relation is the following:

    public function getFkCategory()
{
    return $this->hasMany(Categories::className(), ['category_id' => 'fk_category_id'])
        ->via('CategoryLink');
}

回答1:


DetailView doesn't accept a callable as 'value'. You need to either calculate the string before you call the DetailView:

$string = '';
foreach ($data['fkCategory'] as $cat) {
     $string .= $cat->category_name . '<br/>';
}
...
'value' => $string,

or create a function that does this:

function getCategories() {
    $string = '';
    foreach ($data['fkCategory'] as $cat) {
        $string .= $cat->category_name . '<br/>';
    }
    return $string;
}
...
'value' => getCategories(),

You can even put the function inside the model class you are using with the DetailView and just call it from there.




回答2:


You "can" use a function in DetailView as follows:

'value' => call_user_func(function($model){
                              <your_code_here>
                        }, $model),


来源:https://stackoverflow.com/questions/32203711/has-many-relation-in-detailview

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!