현재 Perfect
프레임 워크로 첫 API를 개발 중입니다. 내가 API를 만들었으니 꽤 오랜 시간이 걸렸으므로 내 SQL
과 API
로직이 약간 녹슬 었음을 인정해야합니다.Join 쿼리에서 구문 분석 객체를 처리하는 방법
구현을 위해 MySQL 데이터베이스를 사용하고 있습니다.
예를 들어 아래 데이터베이스 구조에 대해 설명하겠습니다.
Object와 비슷한 테이블이 있는데, 이것을 Table A
이라고 부릅니다. Table A
의 기본 키는 Varchar
이고 id
입니다.
Table B
및 Table C
이라는 두 개의 다른 테이블이 있습니다. Table A
은 Table B
및 C
과 1 대 다수 관계가 있습니다. 여기서 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 루프