我在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
发布评论