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.

General Questions

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

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

Count DataObject Records


Go to End
Reply

9 Posts   4875 Views

Avatar
DeklinKelly

16 January 2011 at 11:57am Community Member, 197 Posts

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

16 January 2011 at 12:25pm Forum Moderator, 5511 Posts

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

16 January 2011 at 1:22pm Community Member, 197 Posts

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

16 January 2011 at 2:27pm Community Member, 197 Posts

Ooops, there is a problem, Willr.

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

Thanks!

Avatar
Willr

16 January 2011 at 2:39pm Forum Moderator, 5511 Posts

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

16 January 2011 at 3:01pm Community Member, 197 Posts

Perfect, thanks!

Avatar
Stefdv

10 April 2011 at 5:41am Community Member, 110 Posts

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

10 April 2011 at 4:02pm Forum Moderator, 5511 Posts

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

Go to Top