nextras / orm

Orm with clean object design, smart relationship loading and powerful collections.
https://nextras.org/orm
MIT License
310 stars 57 forks source link

QueryBuilder in repository #293

Closed TOMeeeek closed 6 years ago

TOMeeeek commented 6 years ago

Hello, I have a little question. How can I write a query in ORM (Repository) using Nette? I need something similar: SELECT ... IF(quantity>0, 1, 0) as sort_quantity .... ORDER BY sort_quantity

hrach commented 6 years ago

("using Nette" seems quite irrelevant, I understand it as a mistake)

It is true that filtering & sorting on repository layer is quite limited. To allow advanced sorting, you may use custom functions in Orm 3.0 which will allow you implement advanced operations for ICollection.

The simplest impl may look like:

use Nextras\Orm\Mapper\Dbal\CustomFunctions\IQueryBuilderFunction;
use Nextras\Orm\Mapper\Dbal\QueryBuilderHelper;

class ByQuantityOrderingFunction implements IQueryBuilderFunction
{
    public function processQueryBuilderFilter(QueryBuilderHelper $helper, QueryBuilder $builder, array $args): QueryBuilder
    {
        $builder->orderBy('IF(quantity>0, 1, 0)');
        return $builder;
    }
}

Register the function and use it like following $collection->applyFunction(ByQuantityOrderingFunction::class);

Definitely see documentation: https://nextras.org/orm/docs/3.0/collection-functions

TOMeeeek commented 6 years ago

So easy? Thank you for your help.