ERXEOAttribute tagNameAttribute = new ERXEOAttribute(_entity, _tagsRelationship.name() + "." + ERTag.NAME_KEY);
tagNameAttribute.setName("tagName");
fetchAttributes.addObject(tagNameAttribute);
ERXSQLHelper sqlHelper = ERXSQLHelper.newSQLHelper(_entity.model());
EOQualifier tagNameQualifier = new ERXKey<ERTag>(_tagsRelationship.name()).append(ERTag.NAME).in(tagNames);
EOFetchSpecification fetchSpec = new EOFetchSpecification(_entity.name(), tagNameQualifier, null);
EOSQLExpression sqlExpression = sqlHelper.sqlExpressionForFetchSpecification(editingContext, fetchSpec, 0, -1, fetchAttributes);
NSMutableArray<EOAttribute> groupByAttributes = new NSMutableArray<EOAttribute>();
groupByAttributes.addObjectsFromArray(pkAttrs);
sqlHelper.addGroupByClauseToExpression(groupByAttributes, sqlExpression);
sqlHelper.addHavingCountClauseToExpression(EOQualifier.QualifierOperatorEqual, tagNames.count(), sqlExpression);
// MS: Sketchy, I know, but I don't know how to make it do the
// join for me without also having the tag name field selected. I'm sure it's
// possible if I drop down and use lower level API's than
// sqlExpr.selectStatementForAttributes.
sqlHelper.removeSelectFromExpression(tagNameAttribute, sqlExpression);
NSMutableArray<Object> itemPrimaryKeys = new NSMutableArray<Object>();
NSArray<NSDictionary> rawRows = ERXEOAccessUtilities.rawRowsForSQLExpression(editingContext, _entity.model(), sqlExpression, pkAttrs);
EOAttribute pkAttr = pkAttrs.objectAtIndex(0);
for (NSDictionary rawRow : rawRows) {
Object pk = rawRow.objectForKey(pkAttr.name());
itemPrimaryKeys.addObject(pk);
}
NSMutableArray<EOAttribute> tagsFetchAttributes = new NSMutableArray<EOAttribute>();
// MS: We put this in just because we want to force it to do the join ... We have to
// pull them out later.
tagsFetchAttributes.addObjectsFromArray(_entity.primaryKeyAttributes());
ERXEOAttribute tagIDAttribute = new ERXEOAttribute(_entity, _tagsRelationship.name() + ".id");
tagIDAttribute.setName("id");
tagsFetchAttributes.addObject(tagIDAttribute);
tagsFetchAttributes.addObject(tagNameAttribute);
EOAttribute countAttribute = ERXEOAccessUtilities.createAggregateAttribute(editingContext, "COUNT", ERTag.NAME_KEY, _tagEntity.name(), Number.class, "i", "tagCount", "t2");
tagsFetchAttributes.addObject(countAttribute);
EOQualifier idQualifier = new ERXKey<Object>("id").in(itemPrimaryKeys);
EOFetchSpecification tagsFetchSpec = new EOFetchSpecification(_entity.name(), idQualifier, null);
EOSQLExpression tagsSqlExpression = sqlHelper.sqlExpressionForFetchSpecification(editingContext, tagsFetchSpec, 0, -1, tagsFetchAttributes);
NSMutableArray<EOAttribute> tagsGroupByAttributes = new NSMutableArray<EOAttribute>(new EOAttribute[] { tagNameAttribute, tagIDAttribute });
sqlHelper.addGroupByClauseToExpression(tagsGroupByAttributes, tagsSqlExpression);