-
Notifications
You must be signed in to change notification settings - Fork 26
Collection Filter
Yo-An Lin edited this page May 4, 2017
·
1 revision
The Built-in Collection Filter provide a powerful feature that helps you connect the backend collection filtering with your front-end UI by defining filter types, valid values from backend:
use Maghead\Runtime\CollectionFilter;
$posts = new PostCollection;
$filter = new CollectionFilter($posts);
$filter->defineEqual('status', [ 'published', 'draft' ]); // valid values are 'published', 'draft'
$filter->defineContains('content');
$filter->defineRange('created_on', CollectionFilter::String );
$filter->defineInSet('created_by', CollectionFilter::Integer );
$collection = $filter->apply([
'status' => 'published', // get published posts
'content' => ['foo', 'bar'], // posts contains 'foo' and 'bar'
'created_on' => [ '2011-01-01', '2011-12-30' ], // posts between '2011-01-01' and '2011-12-30'
'created_by' => [1,2,3,4], // created by member 1, 2, 3, 4
]);
$collection = $filter->applyFromRequest('_filter_prefix_');
// use '_filter_' as the parameter prefix by default.
$collection = $filter->applyFromRequest();The generated SQL statement is like below:
SELECT m.title, m.content, m.status, m.created_on, m.created_by, m.id FROM posts m WHERE (status = published OR status = draft) AND (content like %foo% OR content like %bar%) AND (created_on BETWEEN '2011-01-01' AND '2011-12-30') AND created_by IN (1, 2, 3, 4)