0

I want to get data like following structure.

Display Record

// Media table like this::-

import UIKit

@objc(Media)

class Media: DBObject {    
    dynamic var media_id : NSNumber!;    
    dynamic var post_id : Post!;    
    dynamic var desc : String!;    
    dynamic var url : String!;
}

I want to get data from "Post" table with Media list from "Media" table.

One post has may be multiple medias or it may be not (media list zero).

Please suggest DBAccess Query to get DBResultSet in Swift.

AtulParmar
  • 4,358
  • 1
  • 24
  • 45

1 Answers1

1

There is a parameter you add to the query, joinTo.

Here is the entry from the header file.

/**
 * Used to include "joined" data within the query string, you must use the tablename.columnname syntax within a where statement

 *
 * @param (Class)joinTo the class you would like to pwrform a SQL JOIN with
 * @param (NSString*)leftParameter the property name that you would like to use within the local object to match against the target
 * @param (NSString*)targetParameter the property within the class you wish to join with that will be matched with the left parameter.
 * @return (DBQuery*) this value can be discarded or used to nest queries together to form clear and concise statements.
 */
- (DBQuery*)joinTo:(Class)joinClass leftParameter:(NSString*)leftParameter targetParameter:(NSString*)targetParameter;

An example in swift, linking two tables (Employee & Login) is below.

Employee.query().joinTo(Login, leftParameter: "login", targetParameter: "Id")

Obviously, the class can't be changed at runtime, so you find the results in the Dictionary object, joinedResults

Although what you are describing is far more to do with relationships, I suggest you look at the one to many examples here:

Relating two objects in DBAccess

So in your specific case, you would add the following method to your Post class.

func media -> DBResultSet {
        return Media.query().whereWithFormat("post_id = %@", withParameters: [self.post_id]).fetch()
    }

This will look up and return the results from the media table.

Community
  • 1
  • 1
Adrian_H
  • 1,548
  • 1
  • 14
  • 27