This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

chris10207
chris10207

from a certain number of items in a table, this is generating a strong exception resulting in a white blank screen do prefer use something like

Db::table( $instance->getTable())->count();

in a trait for example

trait Statisticable {

    public static function getCount()
    {
        $instance = new static;
        return Db::table( $instance->getTable())->count();
    }
}

Last updated

daftspunky
daftspunky

::all()->count() is quite heavy on memory usage.

::count() will result in a count(*) database query.

Good advice!

chris10207
chris10207

the error log is empty with the model::all()->count() - i just have a white blank screen in the backend; yes you are right, most probably too heavy on memory usage. in this particular table i have about 36K items

Goedda
Goedda

Very interesting, though I am having troubles understanding why the $instance->getTable()->count() is so much better than ::count() or ::all()->count().

If I output $instance->getTable(), it is essentially a collection of a lot of methods, count() being one of them. But I fail to see how it "counts" better than the above mentioned methods.

Chris, daftspunk, care to elaborate?

Last updated

jwilson8767
jwilson8767

@Goedda: ::all()->count() retrieves all records, instantiates them as Models, then finally counts the collection. ::count() just does a basic select count(*) from some_table which is can be done very quickly inside the database.

Goedda
Goedda

Thank you, jwilson8767.

chris10207
chris10207

yes, ::all() retrives all the record form a model, ::all()->count() will retrieves all the records from a model and count them (that was my performance issue because i dont need to retrieve all the records in order to count them)

and dont mix up this 2 different codes. ($instance->getTable())->count() with $instance->getTable()->count() im not using the second one.

the code has to be used in a trait for a Model class, i had to use a trait because i want this method getCount() to be available for all my model class first of all.

Second, the attributes $table is not public in the Model class (the parent one), so i had to use the method getTable() from the Model Class, and for this i had to instanciate a fake instance for the current model, so the $instance = new static; because the method getCount() is static

i think you could also write something like (not tested)

public function getCount()
    {
        return Db::table( $this->getTable())->count();
    }

Last updated

1-7 of 7

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.