Skip to content
wan-dall edited this page Sep 5, 2016 · 17 revisions

Previous: Validations - Next: Associations

Some methods, like where, returns Collection objects, which acts like iterators, using the next method or, with PHP 5.4 and above, the foreach loop:

    <?php
        $users = User::where(["level" => 1]);
        var_dump($users->next());

        $users = User::where(["level" => 1]);
        foreach ($users as $user) {
            var_dump($user);      
        }  
    ?>

The conditions can be like the form above or on the following formats:

User::where(["level" => 1]);
User::where(["level = ?", 1]);
User::where("level=1");

The two first forms are more optimized, because the use of prepared statements. The string form will always create an statement to run.

Getting collections

Methods that returns collections are:

  • all - Returns all records
  • where(conditions) - Returns all records with the specified conditions

Modifiers

Some modifier methods can be used with methods that returns collections:

  • limit(integer) - Specify a maximum limit of records returned
  • order(string) - Change the order of the records returned. Overwrite the default order.

Aggregations

These methods makes some aggregations with the all and where methods:

  • count() - Return the count of all records, or the specified on conditions.
  • sum(column) - Return the sum of column.
  • avg(column) - Return the average of column.
  • min(column) - Return the minimum value of column.
  • max(column) - Return the maximum value of column.

Destroying collections

We can destroy all records in a collection using the method destroy:

    <?php
        User::where(array("level"=>1))->destroy();
    ?>

Updating attributes

We can update attributes in a collection using the method updateAttributes:

    <?php
        User::where(array("level"=>1))->updateAttributes(array("level"=>3));
    ?>

Fluent collections

With methods that returns Collection, we can use a fluent operation like this one:

    <?php
        $users = User::where(array("level"=>1))->limit(5)->order("name desc");
    ?>    

The order clause overwrite the default one.

Previous: Validations - Next: Associations

Clone this wiki locally