D-L
D-L

Reputation: 255

SilverStripe 3.1.x - DataList Unique Field value filter / How to use ORM to count items in Grouped List?

In SilverStripe, one can fetch a bunch of records, like so:

$entryRecords = Entry::get()->sort('Email');

If I want to find out how many Entry records I have, I can call the count method on the DataList, like this:

$totalEntryRecords = $entryRecords->count();

If I want to find out how many unique Email addresses are in those records using the SilverStripe ORM in PHP from the DataList without writing a loop and without resorting to running new custom DB query, how would I do that?

Here’s what I've tried so far and it does not work:

GroupedList::create($entryRecords)->groupBy('Email')->Count(); // does not work

I get the following fatal error: PHP Fatal error: Call to a member function Count() on a non-object

The GroupedList API shows that there is a Count method. So not sure why that wouldn't work.

Upvotes: 2

Views: 1422

Answers (3)

cbarberis
cbarberis

Reputation: 31

There is not a method called "distinct" in DataList,

$counter = GroupedList::create(SomeDataObject::get())->GroupedBy('Title')->count();

Is your best option.

Upvotes: 0

wmk
wmk

Reputation: 4626

why not just "select distinct email from ..."?

e.g.

$uniqueEmailsCount =  Entry::get()->distinct()->setQueriedColumns(array('Email'))->count();

I guess this is more performant.

Upvotes: 1

D-L
D-L

Reputation: 255

ok this works...

count(GroupedList::create($entryRecords)->groupBy('Email'));

Upvotes: 2

Related Questions