![](/img/trans.png)
[英]How to Query MySQL JSON Field Values with a Loopback REST API Filter
[英]LoopBack 4 REST API example for getting record with Mysql
我正在學習回送4 ,已經創建了模型,存儲庫和數據源,它也連接到mysql,我可以從http://127.0.0.1:3000/myapi/{id}
檢索結果
在我的默認示例中,通過id獲取是:
@get('/citySchedule/{id}', {
responses: {
'200': {
description: 'Schedule model instance',
content: {'application/json': {schema: {'x-ts-type': Schedule}}},
},
},
})
async findById(@param.path.number('id') id: number): Promise<Schedule> {
return await this.ScheduleRepository.findById(id);
}
但是,我沒有找到任何獲取更多參數數據的教程。
假設schedule
mysql表包含列id
, city_name
, city_code
, date
, task
, item
。
例如,我要獲取"SELECT task, item FROM schedule WHERE city_code=123 AND date=2019-05-01"
我的問題是,如何編寫代碼以在回送控制器上獲取這些數據? 任何示例代碼...
我的期望,我可以從我的api查詢:
http://127.0.0.1:3000/myapi/{city_code}/{date}/
獲取數據結果或
http://127.0.0.1:3000/myapi/{city_name}/{date}/
如果您使用回送cli生成了控制器,則在控制器類中必須有另一個這樣的方法
@get('/citySchedule', {
responses: {
'200': {
description: 'Array of Schedule model instances',
content: {
'application/json': {
schema: {type: 'array', items: {'x-ts-type': Schedule}},
},
},
},
},
})
async find(
@param.query.object('filter', getFilterSchemaFor(Schedule)) filter?: Filter,
): Promise<Schedule[]> {
return await this.ScheduleRepository.find(filter);
}
您可以使用此API來獲取更多的過濾數據。
考慮你的例子
選擇任務,計划中的項目WHERE city_code = 123 AND date = 2019-05-01
對於此查詢,您需要按以下方式訪問API。
GET /citySchedule?filter=%7B%22where%22%3A%7B%22city_code%22%3A123%2C%22date%22%3A%222019-05-01%22%7D%2C%22fields%22%3A%7B%22task%22%3Atrue%2C%22item%22%3Atrue%7D%7D
在這里,過濾器查詢參數值實際上是以下json字符串的url編碼的字符串
{
"where":{
"city_code":123,
"date":"2019-05-01"
},
"fields":{
"task":true,
"item":true
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.