我的数据库结构
部门表包含
- 部门 ID
- 部门
医生表包含
- 部门 ID
Doctor.php//模型名称
public function fields() {
return [
'doctor_id',
'd_name',
'email',
'phone',
'speciality',
'department' => function ($model) {
return $model->department->department; // Return related model property, correct according to your structure
},
'qualification',
'profile_image',
'experience',
];
}
web.php
[
'class' => 'yii\rest\UrlRule',
'controller' => ['doctor','department'],
],
JSON 数据
[
{
"doctor_id":1,
"d_name":"Saurabh Joshi",
"email":"****@gmail.com",
"phone":0,
"speciality":"1",
"department_id":"1",
"qualification":"M.S. (General Surgery) – Marathwada University\n MBBS – Marathwada University",
"profile_image":"Saurabh_Joshi1-1439384488.jpg",
"experience":""
}
]
当我从医生表中获取数据以显示在表单上时,我希望使用部门名称
而不是department_id
。
最佳答案
我不确定,但你可以尝试一下。
在Doctor.php模型中
public function getDepartment()
{
return $this->hasOne(Department::className(), ['department_id' => 'department_id']);
}
和fields()
public function fields() {
return [
'doctor_id',
'd_name',
'email',
'phone',
'speciality',
'department' => 'department.department',
//or
'Department' => 'department' => function () {
return $this->getDepartment->department;
},
'qualification',
'profile_image',
'experience',
];
}
关于mysql - 如何将rest api和yii2中两个数据库表的关系数据显示为json格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32092312/