0

我有一张桌子

CREATE TABLE IF NOT EXISTS `register` (
  `id` int(9) NOT NULL AUTO_INCREMENT,
  `student_id` varchar(15) NOT NULL,
  `title` varchar(100) NOT NULL,
  `name` varchar(250) NOT NULL,
  `email` varchar(50) NOT NULL,
  `gsm` varchar(15) NOT NULL,
  `gender` varchar(10) NOT NULL,
  `birth_date` date NOT NULL,
  `department_id` int(2) NOT NULL,
  `specialization` varchar(150) NOT NULL,
  `level_id` int(2) NOT NULL,
  `reason` varchar(2000) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

与两个表部门和级别有关系

CREATE TABLE IF NOT EXISTS `level` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `level` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

CREATE TABLE IF NOT EXISTS `department` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `department` varchar(300) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

我在注册模型中建立了关系

public function getDepartments() {
        return $this->hasOne(app\models\Department::className(), ['id' => 'department_id']);
    }

但是在 view.php (查看文件)当我使用

<?= DetailView::widget([
        'model' => $model,
        'attributes' => [
            'id',
            'student_id',
            'name',
            'email:email',
            'gsm',
            'gender',
            'birth_date',

 'department' ,
            'specialization',
            'level',
            'reason',
        ],
    ]) ?> ,

部门显示为“未设置”。还 print_r($model);?> 显示[department] =>(即空白) 。这里有什么问题?

4

2 回答 2

2

使用$model->relationName->field_name

[
'attribute' => 'department_id', 
'value' => $model->departments->department
],

并在注册模型中添加部门模型。

于 2016-01-07T09:46:48.437 回答
0

最好将 getDepartments 更改为 getDepartment,因为这是一个 hasOne 关系。

[
  'attribute' => 'department_id', 
  'value' => isset($model->department) ? $model->department->department : ''
]
于 2017-04-06T04:46:23.887 回答