mysql - 如何将rest api和yii2中两个数据库表的关系数据显示为json格式

标签 mysql angularjs rest yii2

我的数据库结构

部门表包含

  1. 部门 ID
  2. 部门

医生表包含

  1. 部门 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/

相关文章:

ajax - 如何在tomcat上允许跨域请求?

java - 如何在 Jersey 中发布通用类型?

MySQL 使用子查询的结果

MySQL 选择字母范围

MySQL 版本 5.6.23 不允许我创建新用户/授予权限

Angularjs ng-model inside ng-repeat via (key,val) 不更新

.net - MySqlCommand调用函数

javascript - 如何定义CSS以获得简单的选项卡式菜单

angularjs - 使用 $location 和 $routeParams 等依赖项测试 Angular 指令

成功休息终点并发出有用的警告