2017-11-23 1 views
0

현재 Perfect 프레임 워크로 첫 API를 개발 중입니다. 내가 API를 만들었으니 꽤 오랜 시간이 걸렸으므로 내 SQLAPI 로직이 약간 녹슬 었음을 인정해야합니다.Join 쿼리에서 구문 분석 객체를 처리하는 방법

구현을 위해 MySQL 데이터베이스를 사용하고 있습니다.

예를 들어 아래 데이터베이스 구조에 대해 설명하겠습니다.
Object와 비슷한 테이블이 있는데, 이것을 Table A이라고 부릅니다. Table A의 기본 키는 Varchar이고 id입니다.

Table BTable C이라는 두 개의 다른 테이블이 있습니다. Table ATable BC과 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 루프

답변

1

가장 좋은 방법에서 새 쿼리를 호출해야하는 경우 '해시 맵'을 사용하는 것입니다. 나는 완벽한 프레임 워크에 익숙하지 해요,하지만 PHP에서 같은 것을 보일 것이다 : 당신은 완벽한 프레임 워크를 파악하는 데 도움이

// Get results from the db: 
$results = $db->execute($query, $params); 
// Define map for controls: 
$map = []; 
// Loop over results/rows 
foreach($results as $row){ 
    // Get unique identifier for the Control model: 
    $controlId = $row['id']; 
    // Check if control is NOT already in map: 
    if(!isset($map[$controlId]){ 
     // Add control to map: 
     $control = [ 
      'id' => $controlId, 
      'description' => $row['description'], 
      'images' => [] 
      // other fields 
     ]; 
     // Add control to map: 
     $map[$controlId] = $control; 
    } 
    else{ 
     // Control exists, retrieve it from the map: 
     $control = $map[$controlId]; 
    } 
    // Retrieve unique identifier of the image: 
    $imageId = $row['image_id']; 
    // Same tactic with hasmap, check if control already has the image, if not add it 
    if(!isset($control['images'][$imageId]){ 
     // add the image to the hashmap: 
    } 
    else{ 
     // Image is already added, the content from the 'update' data is not added yet, handle that part (also with a hash map) 
    } 
} 

희망을

관련 문제