-
Notifications
You must be signed in to change notification settings - Fork 7
Filters
Maphper supports filtering the data:
//find blogs that were posted on a specific date
$filteredBlogs = $blogs->filter(['date' => '2014-04-09']);
//this will only retrieve blogs that were matched by the filter
foreach ($filteredBlogs as $blog) {
echo $blog->title;
}
Filters can be extended and chained together:
//find blogs that were posted with the title "My Blog" by the author with the id of 7
$filteredBlogs = $blogs->filter(['title' => 'My Blog'])->filter(['authorId' => 7]);
//this will only retrieve blogs that were matched by both filters
foreach ($filteredBlogs as $blog) {
echo $blog->title;
}
As well as filtering there are both sort() and limit() methods which can all be chained:
foreach ($blogs->filter(['date' => '2014-04-09']) as $blog) {
echo $blog->title;
}
To find the latest 5 blogs you could use:
foreach ($blogs->limit(5)->sort('date desc') as $blog) {
echo $blog->title;
}
Like any array, you can count the total number of blogs using:
echo 'Total number of blogs is ' . count($blogs);
This will count the total number of blogs in the table. You can also count filtered results:
//Count the number of blogs in category 3
echo count($blogs->filter(['categoryId' => 3]);
You can also use the offset
function for things like pagination when you need to access an offset of results
If you want to filter for a single value you can use the following code (#28)
$mapper->filter(['field' => 'value')->limit(1)->item(0);
Following data is from #6
You can chain any query you like. Imagine a mapper for a table of products. To search for all products with a price between 50.00 and 99.00 OR on sale:
use \Maphper\Maphper::FIND_OR;
use \Maphper\Maphper::FIND_AND;
use \Maphper\Maphper::FIND_LESS;
use \Maphper\Maphper::FIND_GREATER;
$products->filter([
FIND_OR => [
FIND_AND => [
FIND_GREATER => [
'price' => 50
],
FIND_LESS => [
'price' => 100
]
],
'onSale' = 1
]
]);
Which will generate the query SELECT * FROM products WHERE (price > 50 AND price < 100) OR onSale=1
Any value can take an array to find more than one record
$products->filter(['categoryId' => [1, 4, 6, 8]);
Which will generate SELECT * FROM products WHERE categoryID IN(1, 4, 6, 8)