在休息响应中包含关系数据的Yii方式是什么?
场景:我有一个客户模型和一个带有客户地址的模型,我希望my-application.com/customers
返回以下内容:
[
{
"id": 1,
"name": "Customer #1",
"org_no": "2342342",
"created_at": "2017-04-28 00:00:00",
"created_by": 1,
"updated_at": "2017-04-28 00:00:00",
"updated_by": 1,
"customer_since": "2016-10-10 00:00:00",
"next_follow_up": "2017-04-29 00:00:00",
"email_invoice": 1,
"invoice_email": "invoice@customer.com",
"invoice_address": 1
"addresses": [
{
"street": "teststreet 1",
"postal": 12345
}
]
}
]
答案 0 :(得分:2)
假设您在模型Customer
中有一个关系可以获取所有客户地址,即getAdresses
,您应该在那里实施extraFields()
方法:
public function extraFields() {
return [
'addresses' => 'addresses',
];
}
然后,要包含该关系数据,您可以像这样调用您的API:
application.com/customers?expand=addresses