/**
* Convenience method that returns the count of related records using raw SQL
*/
public static Number countRelatedEnterpriseObjects(EOEnterpriseObject sourceEO, String relationshipKey) {
// First make sure the relationship is to-many and has unary keys
EOEntity sourceEntity = EOModelGroup.defaultGroup().entityForObject(sourceEO);
String modelName = sourceEntity.model().name();
EORelationship rel = sourceEntity.relationshipNamed(relationshipKey);
NSArray destAttributes = rel.destinationAttributes();
if (rel == null || !rel.isToMany()) {
throw new RuntimeException("No to-many relationship found for key: " + relationshipKey);
}
if (destAttributes.count() != 1) {
throw new RuntimeException("This method can only be used with entities having unary primary keys.");
}
//--------------------------------------------------
// Count the number of related rows using raw SQL
//--------------------------------------------------
EOEntity destEntity = rel.destinationEntity();
NSArray destPKAttributes = destEntity.primaryKeyAttributes();
String destPK = ((EOAttribute)destPKAttributes.lastObject()).columnName();
String destFK = ((EOAttribute)destAttributes.lastObject()).columnName();
// Build the SQL statement to return the row count
String sql = "SELECT COUNT(" + destPK + ") FROM " + destEntity.externalName() +
" WHERE " + destFK + " = " + unaryPKValueForObject(sourceEO) + ";";
NSArray rows = EOUtilities.rawRowsForSQL(sourceEO.editingContext(), modelName, sql, new NSArray("rowCount"));
if (rows.count() > 0) {
Number rowCount = (Number)((NSDictionary)rows.lastObject()).objectForKey("rowCount");
return rowCount;
}
return null;
}
/**
* Returns the PK of the object as a string value.
*/
public static String unaryPKValueForObject(EOEnterpriseObject eo){
NSDictionary d = EOUtilities.primaryKeyForObject(eo.editingContext(), eo);
Number n = (Number)d.objectForKey("oid");
return n.toString();
}