Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We're retiring the forums!

The SilverStripe forums have passed their heyday. They'll stick around, but will be read only. We'd encourage you to get involved in the community via the following channels instead:

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Count DataObject Records


Go to End


9 Posts   8634 Views

Avatar
DeklinKelly

Community Member, 197 Posts

16 January 2011 at 11:57am

What is the best way to count the total matching records?

This works, but it is beneficent:

$records = DataObject::get($obj, $filter, $sort, $join);
$recordsCount = count($records);

I don't need to run the full query. I only want to count the total available records.

Is there a graceful way to do something like this?

$recordsCount = DataObject::count($obj, $filter, $sort, $join);

Avatar
Willr

Forum Moderator, 5523 Posts

16 January 2011 at 12:25pm

Quickest way is to do a direct DB::query(), using DataObject::get to just get a count is a very bad way of doing things.

$count = DB::query("SELECT COUNT(*) FROM Table WHERE Foo LIKE 'Bar'")->value();

Avatar
DeklinKelly

Community Member, 197 Posts

16 January 2011 at 1:22pm

Thanks! That is what I needed. It also seems to work if you use 'ID' instead of *

$count = DB::query("SELECT COUNT('ID') FROM Table WHERE Foo LIKE 'Bar'")->value();

Avatar
DeklinKelly

Community Member, 197 Posts

16 January 2011 at 2:27pm

Ooops, there is a problem, Willr.

Your idea counts unpublished items. Do we need a join? If so, what?

Thanks!

Avatar
Willr

Forum Moderator, 5523 Posts

16 January 2011 at 2:39pm

Your idea counts unpublished items. Do we need a join? If so, what?

Well it depends what your counting, if its SiteTree objects then use SiteTree_Live as the table then rather than SiteTree.

Avatar
DeklinKelly

Community Member, 197 Posts

16 January 2011 at 3:01pm

Perfect, thanks!

Avatar
Stefdv

Community Member, 110 Posts

10 April 2011 at 5:41am

Hello,

But what do i call in my template if i just want to show the total numbers of objects?


 function TotalDogs(){
$count = DB::query("SELECT COUNT(*) FROM Dog")->value();
return $count;
	}

if i look with

var_dump($count)
i get a string(2)"175" . How do i show this in my template ?

thanks

Avatar
Willr

Forum Moderator, 5523 Posts

10 April 2011 at 4:02pm

You can then use $TotalDogs in your template to get that string (provided the function is in scope).

Go to Top