-
Notifications
You must be signed in to change notification settings - Fork 29
Collections
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.
Methods that returns collections are:
- all - Returns all records
- where(conditions) - Returns all records with the specified conditions
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.
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.
We can destroy all records in a collection using the method destroy
:
<?php
User::where(array("level"=>1))->destroy();
?>
We can update attributes in a collection using the method updateAttributes
:
<?php
User::where(array("level"=>1))->updateAttributes(array("level"=>3));
?>
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.