0

I have a model Category with the relationship property articles with is an NSOrderedSet. Now I want to get all Categories with the articles where a certain condition is fulfilled, in SQL I would write:

SELECT * 
FROM Category AS cat
JOIN Article AS art ON art.categoryId = cat.categoryId AND art.gender='m';

I tried with:

NSPredicate(format: "articles.gender like %@ OR articles.gender = %@", gender.lowercased(), "n")

I get the following error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'to-many key not allowed here'

Complete code:

    let ctx = self.Context()

    var gender = UserDefaults.standard.string(forKey: "gender_preference") ?? "*"
    if gender.uppercased() == "N" { gender = "*" }

    // Create Fetch Request
    let fetchRequest: NSFetchRequest = ArticleCategory.fetchRequest()
    let predicate = NSPredicate(format: "articles.gender like %@ or articles.gender = %@", gender, "n")
    fetchRequest.predicate = predicate

    // sort by name
    let sort = NSSortDescriptor(key: "name", ascending: true)
    fetchRequest.sortDescriptors = [sort]

    do {

        let result = try ctx.fetch(fetchRequest)
        return result

    } catch {

        print(error)

    }

    return []

Kind Regards

EDIT:

Model Relationship

Mario
  • 978
  • 2
  • 11
  • 31
  • Have you tried with `ANY` ? `NSPredicate(format: "ANY articles.gender like %@ OR articles.gender = %@", gender.lowercased(), "n")` – Mat Apr 12 '17 at 20:25
  • Sorry; yes I tried, same for SOME and ALL – Mario Apr 12 '17 at 20:41

1 Answers1

0

I find it's more reliable to use SUBQUERY rather than ANY, ALL, NONE or SOME, particularly with compound clauses. Fetching Categories where ANY of its articles meet a condition is equivalent to fetching if the count of articles meeting the condition is greater than zero:

let predicate = NSPredicate(format: "SUBQUERY(articles, $a, $a.gender like %@ OR $a.gender == %@).@count > 0", gender, "n")
pbasdf
  • 21,386
  • 4
  • 43
  • 75
  • The query compiles, but it's not what I need. I want to filter the articles by the gender. Not get the categories which have more than 0 articles... – Mario Apr 12 '17 at 22:25
  • @Mario In which case, fetch Articles not ArticleCategories, and use a simpler predicate: `let fetchRequest: NSFetchRequest = Article.fetchRequest() let predicate = NSPredicate(format: "gender like %@ or gender = %@", gender, "n")` – pbasdf Apr 12 '17 at 22:55