zoid / doctrine-filter-objects
此包最新版本(dev-master)没有可用的许可证信息。
dev-master
2019-07-28 20:21 UTC
Requires
- php: >=7.1
- doctrine/orm: ^2.7
Requires (Dev)
- phpunit/phpunit: ^8.3@dev
This package is not auto-updated.
Last update: 2024-09-30 23:34:59 UTC
README
包装在Doctrine\ORM的QueryBuilder上。提供易于使用、可定制的类来指定WHERE
和ORDER
参数。
过滤
创建通用过滤器
$data = [
'name' => 'David',
'location' => 'USA',
'age' => 26,
'position' => 'IT'
];
$filter = new QueryFilter($data);
// You can specify the relations between parameters
// Untouched parameters will be appended to the end of query with AND operator
$filter ->and('name')
->and('location')
->or('age', Where::NOT_EQUAL)
->end()
->and('position', Where::LIKE);
// Return DQL Where part with prefixed columns
echo $filter->getStatement('c');
// "c.name = David AND ((c.location = USA OR c.age <> 26) AND c.position LIKE Manager)"
在查询构建器中使用过滤器
由于$filter->getStatement()
返回string
,因此它很容易在Doctrine QueryBuilder
中使用。
$qb = $this->em->createQueryBuilder();
$qb ->select('p')
->from(Product::class, 'p')
->where($filter->getStatement('p');
您可以通过使用预定义类FilterApplier
来跳过传递$prefix
参数
$qb = $this->em->createQueryBuilder();
$qb ->select('p')
->from(Product::class, 'p');
$applier = new FilterApplier($qb);
$applier->filter($filter);
创建自定义过滤器
您可以通过实现IQueryFilter
接口来创建自定义过滤器
class ActiveProductsFilter implements IQueryBuilderFilter
{
public function getStatement(string $prefix): string
{
$expr = new Expr();
return $expr->andX(
$expr->eq("{$prefix}.removed", 'FALSE'),
$expr->eq("{$prefix}.visible", 'TRUE')
);
}
}
并轻松地在FilterApplier
中使用它。
$qb = $this->em->createQueryBuilder();
$qb ->select('p')
->from(Product::class, 'p');
$applier = new FilterApplier($qb);
$applier->filter($filter)
->filter(new ActiveProductsFilter());
排序
使用QueryOrder
QueryOrder是一个简单的对象,用于存储QueryBuilder的排序选项。
$order = new QueryOrder(['position', 'ASC'])
$qb = $this->em->createQueryBuilder();
$qb ->select('p')
->from(Product::class, 'p');
// By calling
$qb->orderBy($order->getColumnName('p'), $order->getOrder());
// By FilterApplier
$applier->order($order);