Core Data仅返回单个对象,多关联条件查询问题求助
Hey there! Let's figure out why your Core Data query is only returning a single Producto instead of all matches that meet your criteria.
First, let's map your SQL logic to Core Data's object-oriented approach. Your SQL joins Producto with Categoria and Supermercado to find items where both related entities have specific names. The key here is writing the right NSPredicate to replicate that logic—since Core Data works with object relationships, not raw SQL joins.
Common Issues Causing Single-Object Results
Most likely, your predicate was written incorrectly (e.g., using the wrong relationship path or operator) or your data model relationships aren't configured properly. Let's fix that.
Step 1: Verify Your Data Model Relationships
Make sure your model has the correct relationships set up:
Productoshould have a relationship toCategoria(e.g.,categoriasfor one-to-many,categoriafor one-to-one)Productoshould have a relationship toSupermercado(e.g.,supermercadosfor one-to-many,supermercadofor one-to-one)- Ensure inverse relationships are defined—Core Data relies on these for accurate querying.
Step 2: Write the Correct Predicate
Choose the predicate that matches your relationship type:
Case 1: One-to-One Relationships
If each Producto links to exactly one Categoria and one Supermercado, use this simple predicate:
let fetchRequest: NSFetchRequest<Producto> = Producto.fetchRequest() fetchRequest.predicate = NSPredicate(format: "categoria.name == %@ AND supermercado.name == %@", "carne", "Mercadona")
Case 2: One-to-Many Relationships
If a Producto can have multiple Categoria or Supermercado entries, use SUBQUERY to explicitly check that at least one of each matches the required names:
let fetchRequest: NSFetchRequest<Producto> = Producto.fetchRequest() let predicate = NSPredicate(format: """ SUBQUERY(categorias, $cat, $cat.name == %@).@count > 0 AND SUBQUERY(supermercados, $sup, $sup.name == %@).@count > 0 """, "carne", "Mercadona") fetchRequest.predicate = predicate
This guarantees the Producto has at least one Categoria named "carne" and at least one Supermercado named "Mercadona".
Step 3: Execute the Query Properly
Make sure you're fetching all results without unintended limits. Here's how to run the query safely:
do { let matchingProductos = try managedContext.fetch(fetchRequest) print("Found \(matchingProductos.count) matching productos") // Process your results here } catch { print("Fetch error: \(error.localizedDescription)") }
Why Your Previous Query Failed
If you used something like ANY categorias.name == %@ AND ANY supermercados.name == %@, that should work for one-to-many—but double-check for typos in relationship names (e.g., categoria instead of categorias) or accidental fetchLimit settings on your request. Those small mistakes can easily filter results down to just one object.
内容的提问来源于stack exchange,提问作者user9074882

