我有一张桌子
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 ;
我在Register模型中建立了关系
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);?&gt;显示[department] =>
(即空白)。这是什么问题?
答案 0 :(得分:2)
使用$model->relationName->field_name
:
[
'attribute' => 'department_id',
'value' => $model->departments->department
],
在注册模型中添加部门模型。
答案 1 :(得分:0)
更好地将getDepartments更改为getDepartment,因为这是一个hasOne关系。
[
'attribute' => 'department_id',
'value' => isset($model->department) ? $model->department->department : ''
]