我刚刚开始使用 yii,但我对 php 框架并不陌生。但是现在我遇到了这个问题:
我有两个模型/数据库:
部门: http://s7.directupload.net/images/120610/alemicys.png
员工: http://s1.directupload.net/images/120610/hxerdm8t.png
我只是想在此员工 View 中显示部门的实际名称。因此,我希望有“司法部”,而不是“部门”列中的 1。
这就是我的数据库的样子: http://s1.directupload.net/images/120610/7wupindz.png
提前致谢! 约翰
最佳答案
将其添加到员工 GridView 的 columns
中属性:
// this is in place of just 'departmentId',
array(
'name'=>'departmentId', // name of the foreign key attribute
'value'=>'$data->department->name', // access the 'name' attribute of the related record through relation named 'department', the current record is represented by '$data'
'type'=>'raw' // data is of raw type
),
阅读CDataColumn了解如何修改上面的数组。
注意:由于您只要求显示,因此上面的代码将起作用,如果您希望此列的过滤器起作用,则必须
- 修改员工模型的搜索功能(或无论您在哪里进行搜索),以将输入字符串映射到departmentId或
- 编写一些 JavaScript 将相关部门的 ID(而不是字符串)发送到搜索。
现在,过滤器仅适用于 DepartmentId(即整数),而不适用于名称(字符串)。
您也可以这样做来代替上面的代码:
//again in place of departmentId
'department.name' // using the 'department' relation, accessing its 'name'
但是要获取过滤器将很困难(您将不得不再次使用数组),并且列标题也将成为部门模型的名称的attributeLabel> 属性。可以使用以下格式更改标题: 'name:type:header'
,因此您可以执行以下操作: 'department.name:Department'
大部分详细信息都可以在我包含的文档链接中找到。
关于yii - 如何在yii中链接数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10969137/