首页
登录 | 注册

Yii2 rest 联表数据查询

在model里写

public function fields()

    {
        return [

            'id',

            'company_id',   

            'type_id',       

            'company'=>function () {
               return Company::findOne($this->company_id);
            },
            'create_time'=> function () {
               return Yii::$app->formatter->asDatetime($this->create_time,'php:Y-m-d H:i:s');
            },
            'update_time'=> function () {
               return Yii::$app->formatter->asDatetime($this->update_time,'php:Y-m-d H:i:s');
            },
        ];

    }

public function getType()
    {
        return $this->hasOne(Type::className(), ['id' => 'type_id']);
    }

http://api.test.cn/v1/test

{

"success": true,
"code": 200,
"data": {
"job_id": 2,
"company_id": 2,
"type_id": 2,
"company": {
"id": 2,
"company_name": "互联网公司",
"create_time": "2018-03-21 15:34:44",
"update_time": "2018-03-21 17:18:02"
},
"create_time": "2018-03-23 11:17:22",
"update_time": "2018-03-23 11:33:12"
},
"message": "OK",
"extra": null
}


http://api.test.cn/v1/test?expand=type

{
"success": true,
"code": 200,
"data": {
"job_id": 2,
"company_id": 2,
"type_id": 2,
"company": {
"id": 2,
"company_name": "互联网公司",
"create_time": "2018-03-21 15:34:44",
"update_time": "2018-03-21 17:18:02"
},
"create_time": "2018-03-23 11:17:22",
"update_time": "2018-03-23 11:33:12"
},
"type": {
"id": 2,
"type_name": "高级会员"
},
"message": "OK",
"extra": null
}


2020 jeepxie.net webmaster#jeepxie.net
10 q. 0.009 s.
京ICP备10005923号