Search code examples
swiftparse-platformparse-serverpfquery

How to use Relationship to retrieve image on Parse Server using swift


new to parse, I went through documentation yet I am not grasping the concept of relations...

I have a 1 to Many relation (product -> many color variations).

On parse, under my class "product" I have the following columns: Brand, Size, Price, Color.

The color cell is a relation that hooks to a "color" class, which contains: Color_Name, Color_Image(as a file).

How do i access the color_name & color_image? I am using the code below, but am returning nil.

func searchCategoryItems(){

categoryType = "basketball"

let query:PFQuery = PFQuery(className: "products")
                query.includeKey("color")
                let productQuery = query.whereKey("type", equalTo:self.categoryType)

                productQuery.findObjectsInBackgroundWithBlock {
                    (objects, error) -> Void in

                    for object in objects! {
                        let brandName:String? = (object as PFObject)["brand"] as? String
                        let itemName:String? = (object as PFObject)["item_name"] as? String
                        let sku:String? = (object.objectId! as String)
                        let colors:String? = (object as PFObject)["color_name"] as? String
                        if colors != nil{
                        self.productColorArray.append(colors!)
                        print("colors work?", colors)
                        }

                        if brandName != nil {
                            self.productBrandArray.append(brandName!)
                        }
                        if itemName != nil{
                            self.productItemNameArray.append(itemName!)
                        }
                        if sku != nil{
                            self.productSkuArray.append(sku!)
                        }


                    }

                    self.searchTableView.reloadData()
                }
                self.searchTableView.insertRowsAtIndexPaths([NSIndexPath(forRow:0,inSection:0)], withRowAnimation: UITableViewRowAnimation.Automatic)
            }
    }

This is what my parse dashboard is se up like:

products class

color class


Solution

  • You need to do an additional relational query.

    let product = ...//specify a product. e.g. object in objects
    let relation = product.relationForKey("color")
    let innerQuery = relation.query()
    //then executing the innerQuery