我有一个领域:
class Train: RLMObject {
dynamic var stationDeparture: Station?
dynamic var trainId = 0
dynamic var route = RLMArray(objectClassName: Route.className())
override class func primaryKey() -> String {
return "trainId"
}
}
class Route: RLMObject {
dynamic var numberInRoute = 0
dynamic var station: Station?
var owners: [Train] {
return linkingObjectsOfClass("Train", forProperty: "Route") as! [Train]
}
}
class Station: RLMObject {
dynamic var code = 0
dynamic var name = ""
override class func primaryKey() -> String {
return "code"
}
dynamic var relatedStations = RLMArray(objectClassName: Station.className())
}
我试图在[{1}} class Train: RLMObject
为dynamic var stationDeparture: Station?
获取车站和车站相关车站的所有列车。起初我从相关站的代码中创建了一个字符串,然后在谓词中使用“IN”进行查询。
这个功能很有用,很难看但是有效!:
func trainsForDepartureStation (station: Int) -> RLMResults? {
let stations = Station.objectsWhere("code == \(station)")
let related = stations.lastObject() as! Station
if related.relatedStations.count > 0 {
var st = ""
st += "{\(station)"
for id in 0...related.relatedStations.count-1 {
st += ", \(related.relatedStations[id].code)"
}
st += "}"
let trains = Train.objectsWhere("stationDeparture.code IN \(st)")
return trains
} else {
let trains = Train.objectsWhere("stationDeparture.code == \(station)")
return trains
}
}
但是当我试图在火车的所有路线上使用所有车站的火车时,它也不起作用。
let trains = Train.objectsWhere("ANY route.station.relatedStations.code IN \(st)")
错误是:
'Invalid predicate', reason: 'Predicate with ANY modifier must compare a KeyPath with RLMArray with a value'
如何针对此问题进行嵌套查询? 我是快速的,客观的 - с和领域(
答案 0 :(得分:0)
您可能已经猜到,您必须将该查询分解为多个查询。首先,让我们重构trainsForDepartureStation()
以更好地了解它目前在做什么:
func trainsForDepartureStation(station: Int) -> RLMResults? {
let stations = Station.objectsWhere("code == \(station)")
if let related = stations.lastObject() as? Station where related.relatedStations.count > 0 {
return Train.objectsWhere("stationDeparture IN %@", related.relatedStations)
} else {
return Train.objectsWhere("stationDeparture.code == \(station)")
}
}
好的,现在让我们改变一下,返回“列车所有列车所有车站的列车”:
func trainsForDepartureStation(station: Int) -> RLMResults? {
let stations = Station.objectsWhere("code == \(station)")
if let related = stations.lastObject() as? Station where related.relatedStations.count > 0 {
let allRelatedStations = Station.objectsWhere("relatedStations IN %@", related.relatedStations)
let allRelatedRoutes = Route.objectsWhere("station IN %@", allRelatedStations)
return Train.objectsWhere("ANY route IN %@", allRelatedRoutes)
} else {
let allRelatedRoutes = Route.objectsWhere("station == %@", stations.lastObject() as! Station)
return Train.objectsWhere("ANY route IN %@", allRelatedRoutes)
}
}
答案 1 :(得分:0)
只有一个错误,这一部分:
let allRelatedStations = Station.objectsWhere("relatedStations IN %@", related.relatedStations)
let allRelatedRoutes = Route.objectsWhere("station IN %@", allRelatedStations)
应替换为:
let allRelatedRoutes = Route.objectsWhere("station IN %@", related.relatedStations)
因为allRelatedStations没有获取相关的站点,而只是再次获取父站点