在DetailView中的Has_many关系 [英] Has_many relation in DetailView

查看:83
本文介绍了在DetailView中的Has_many关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在gridview中使用了以下代码,并且运行良好:

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

这将在表格单元格的新行上显示所有项目的类别.但是,如果我想在DetailView中显示类似内容,则无法正常工作. Detailview给我一个错误:

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

那么如何在DetailView中访问has_many关系?

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

关系如下:

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

推荐答案

DetailView不接受可调用项作为值".您需要先计算字符串,然后再调用DetailView:

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

您甚至可以将函数放在与DetailView一起使用的模型类中,然后从那里调用它.

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

这篇关于在DetailView中的Has_many关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆