Has_many relation in DetailView

2019-07-08 20:34发布

问题:

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),