2

I am querying data using the code below. In the database, there are duplicate entries for 'title', how can I get distinct values?

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'institutions';
$query = craft()->elements->buildElementsQuery($criteria);
//$query->setDistinct('title');
$query->order('title asc');

$queryResults = $query->queryAll();
$institutions = EntryModel::populateModels($queryResults);

return $institutions;
2
  • Are you sure that you don't just have multiple entries with the same title? The query returned by buildElementsQuery() is already prepped to fetch only unique entries. Commented Jul 31, 2016 at 14:46
  • Yeah, there is. I only need unique records. Commented Jul 31, 2016 at 16:40

2 Answers 2

2

The query returned by buildElementsQuery() is already prepped to fetch unique entries. But it’s possible for two distinct entries to have the same title, which is why it may look like duplicate entries are being returned.

To only fetch entries with unique titles, do this:

$query->group('content.title');
1

The setDistinct method should be passed a boolean value.

http://www.yiiframework.com/doc/api/1.1/CDbCommand#setDistinct-detail

If that doesn't work, you may need to use the selectDistinct method to override the SELECT portion of the query. By default, this sets distinct = true.

http://www.yiiframework.com/doc/api/1.1/CDbCommand#selectDistinct-detail

1
  • Didnt work. I did: $criteria->selectDistinct = 'title'; and $query->selectDistinct = 'title'; Commented Jul 31, 2016 at 16:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.