【发布时间】:2017-11-23 22:01:09
【问题描述】:
我目前正在使用Perfect 框架开发我的第一个API。我自己制作 API 已经有一段时间了,所以我必须承认我的 SQL 和 API 逻辑有点生疏。
我正在使用 MySQL 数据库来实现。
为了举例,我将在下面解释我的数据库结构;
我有一个类似于对象的表,我们称之为Table A。 Table A 有一个基于id 的Varchar 作为主键。
还有另外 2 个表,我们称它们为 Table B 和 Table C。 Table A 与 Table B 和 C 具有一对多关系。其中表A的id是外键。
我正在尝试做的是通过一个查询获取所有内容并将其转换为我后端中的一个对象。
通过使用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 循环中调用一个新查询
【问题讨论】:
标签: mysql swift database join perfect