yii - 如何在yii中链接数据

标签 yii

我刚刚开始使用 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了解如何修改上面的数组。

注意:由于您只要求显示,因此上面的代码将起作用,如果您希望此列的过滤器起作用,则必须

  1. 修改员工模型的搜索功能(或无论您在哪里进行搜索),以将输入字符串映射到departmentId或
  2. 编写一些 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/

相关文章:

php - 向远程sqlite插入数据

php - Yii - 使用关系中定义的范围的关系

php - 即使从具有 Yii2 行为的 matchCallback 返回 false 时也设置自定义 denyCallback

php - YII 迁移和表列的默认值

php - 使用 PostgreSQL 在 Yii Framework 中设置非默认架构

javascript - Yii 提交按钮 i18n

php - 在 Yii 的文本字段中显示错误消息

php - 如何在两条记录后添加 HTML 元素 zii.widgets.CListView widget Yii

php - 我想将 YII 框架与两个数据库连接,但它抛出 CDbConnection failed Incorrect database name

yii - dropzone.js 不上传 .doc、.xls、.xlsx 文件格式