[英]LoopBack 4 REST API example for getting record with Mysql
i'm learning loopback 4 , i have created model, repository and datasource, it also connected to mysql and i can retrieve results from http://127.0.0.1:3000/myapi/{id}
我正在学习回送4 ,已经创建了模型,存储库和数据源,它也连接到mysql,我可以从
http://127.0.0.1:3000/myapi/{id}
检索结果
in my default example getting by id is : 在我的默认示例中,通过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);
}
However, i didnt found any tutorial for getting data with more parameters. 但是,我没有找到任何获取更多参数数据的教程。
let say mysql table of schedule
has contain column id
, city_name
, city_code
, date
, task
, item
. 假设
schedule
mysql表包含列id
, city_name
, city_code
, date
, task
, item
。
for example, i want to get "SELECT task, item FROM schedule WHERE city_code=123 AND date=2019-05-01"
例如,我要获取
"SELECT task, item FROM schedule WHERE city_code=123 AND date=2019-05-01"
my question, how to write code to get those data at loopback controller ? 我的问题是,如何编写代码以在回送控制器上获取这些数据? any example code...
任何示例代码...
my expectations, i can query from my api : 我的期望,我可以从我的api查询:
http://127.0.0.1:3000/myapi/{city_code}/{date}/
to get data results or http://127.0.0.1:3000/myapi/{city_code}/{date}/
获取数据结果或
http://127.0.0.1:3000/myapi/{city_name}/{date}/
If you have generated your controller using loopback cli, you must have got another method in controller class like this 如果您使用回送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);
}
You can use this API to fetch more filtered data. 您可以使用此API来获取更多的过滤数据。
Considering your example 考虑你的例子
SELECT task, item FROM schedule WHERE city_code=123 AND date=2019-05-01
选择任务,计划中的项目WHERE city_code = 123 AND date = 2019-05-01
for this query, you need to hit the API like this. 对于此查询,您需要按以下方式访问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
Here, the filter query parameter value is actually url encoded string for the below json string 在这里,过滤器查询参数值实际上是以下json字符串的url编码的字符串
{
"where":{
"city_code":123,
"date":"2019-05-01"
},
"fields":{
"task":true,
"item":true
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.