How do you represent a many-to-many relationship with a predicate when setting up a fetch controller?

I have this fetch results controller I'm using to fetch data into a view. The fetch controller does manage to fetch managedObjects but the problem is that it's fetching every "Recipe" entity. I would like it to only fetch recipes that are connected to the category I specified. I think my predicate might be wrong but I dont know how to fix it. Is there anyone who can point me in the right direction? Thanks


// I pass category from a previous view to this view which also sets recipes
var category: FoodCategory? {
        didSet {
            recipes = category?.recipes
        }
    }

var recipes: NSSet?

lazy var recipeFetchedResultsController: NSFetchedResultsController = { () -> NSFetchedResultsController<NSFetchRequestResult> in
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Recipe")
        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
        
//     is this correct???
        let hasCategory = NSPredicate(format: "name = %@", category!.name!)

        (self.recipes)?.filter({ (hasCategory) -> Bool in
            (self.recipes?.contains(category))!
        })

        let delegate = UIApplication.shared.delegate as! AppDelegate
        
        let context = delegate.managedObjectContext

        let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)

        frc.delegate = self

        return frc
    }()

Nevermind, I found the solution. I had to use a subquery in my string format. This took a bit of time to understand how to set it up but this post [SUBQUERY Is Not That Scary] from Maciek Czarnik was really helpful. Here's how I set up:


fetchRequest.predicate = NSPredicate(
            format: "SUBQUERY(" +
                "categories, " +
                "$foodcategory, " +
                "$foodcategory.name ==[cd] \"\(category!.name!)\"" +
            ").@count > 0"
            
        )
How do you represent a many-to-many relationship with a predicate when setting up a fetch controller?
 
 
Q