我目前正在使用该Perfect框架开发我的第一个 API。自从我自己制作 API 以来已经有一段时间了,所以我必须承认我SQL的API逻辑有点生疏。
我正在使用 MySQL 数据库来实现。
为了举例,我将在下面解释我的数据库结构;
我有一个类似于对象的表,我们称之为Table A. Table A有一个Varchar基础id作为主键。
还有 2 个其他表,我们称它们为Table B和Table C。和Table A都有一对多的关系。其中of 表是外键。Table BCidA
我想要做的是通过一个查询获取所有内容并将其转换为我后端的一个对象。
通过使用outer joins我正在调用以检索所有必需的数据。
SELECT control.id, control.type, control.description, control.address, control.city, control.created, control.updated, control.latitude, control.longitude, images.id AS image_id, images.image, images.description AS image_description, updates.id AS update_id, updates.still_present, updates.created_at AS update_created
FROM Control control left outer join control_images images
ON control.id=images.control_id
left outer join Control_Updates updates
ON control.id=updates.control_id
现在是我的问题,将这些数据存储在包含更新数组和图像数组的对象中的最佳方法是什么。
在编写连接查询之前,我只尝试从中获取值,Table A我使用以下代码将结果转换为我想要的对象。
let result = mysql.storeResults()
let checkResult = self.checkResult(result: result, response: response)
response = checkResult.response
var controls: [Control] = []
while let row = result?.next() {
let type = Types(rawValue: row[1].unwrap)!
let control = Control(id: row[0].unwrap, type: type, description: row[2].unwrap, address: row[3].unwrap, city: row[4].unwrap, latitude: Double(row[7].unwrap).unwrap, longitude: Double(row[8].unwrap).unwrap)
controls.append(control)
}
显然,这只会返回除了图像和更新之外的重复对象。
我想知道这是否是最好的方法,或者我是否应该在 while 循环中调用一个新查询