Skip to content
dougkusanagi edited this page Aug 22, 2018 · 5 revisions

Previous: Relations - Next: Pagination

Scopes

Scopes are easier ways to remember and execute some well-defined query behaviours. They are created using the scope name and one of the two ways explained below.

Using an array

We can create scopes sending an array with the conditions, like:

<?php
User::scope("first_level",array("level"=>1));
foreach(User::first_level() as $user) {
   echo $user->name;
}
?>

Using a callable

We can create scopes sending a callable (anonymous function, closure), like:

<?php
User::scope("by_level",function($args) { return "level=".$args[0]; });
echo "There are ".User::by_level(1)->count()." users on the first level";

User::scope("by_level_and_date",function($args) { return "level=".$args[0]." and created_at<'".$args[1]." 23    :59:59'"; });
echo "There are ".User::by_level_and_date(2,date("Y-m-d"))->count()." users on the second level, created before today";
?>

Previous: Relations - Next: Pagination

Clone this wiki locally