The query sorting bundle allows you to sort data from QueryBuilder and the Database

Overview

Query Sorting Bundle

Scrutinizer Code Quality GitHub Workflow Status Code Intelligence Status

What does it do? :)

The query sorting bundle allows you to sort data from QueryBuilder and the Database. you can sort multiple columns at the same time and also you can sort relation fields with two-level deep and without any join in your query builder.

Installation:

composer require bugloos/query-sorting-bundle

Compatibility

  • PHP v7.4 or above
  • Symfony v4.4 or above

Usage

Suppose our database has the following tables with the following relations

Service running preview

Now we want to show the Book entity by sorting

We want sort Book entity by price column, so we can send sort data by Querystring or make inline with array like this:

/*
 * Sort book by price ascending
*/
//Get api/book/index?order[price]=ASC
OR
$orders = [
    'price' => SortType::ASC,
];

/*
 * Sort book by price descending
*/
//Get api/book/index?order[price]=DESC
OR
$orders = [
    'price' => SortType::DESC,
];

You just need to add Sorting class in controller the call sort method:

use Bugloos\QuerySortingBundle\Service\QuerySorting;

The following code is in Book controller.

As you see, At first you should call for() method and pass QueryBuilder as parameter to this method

Then call parameters() method and pass orders request items

At the end you should call sort() method to run sorting

The return of sort method is Query Builder, so you can add anything else to Query Builder after sorting.
public function index(
    Request $request,
    BookRepository $bookRepository,
    QuerySorting $querySorting
): Response {
    $queryBuilder = $bookRepository->createQueryBuilder('b');
    
    $queryBuilder = $querySorting->for($queryBuilder)
        ->parameters($request->get('order'))
        ->sort()
    ;
    
    return $queryBuilder->getQuery()->getResult();
}

If you want to sort the ManyToOne relation field or one level deep relation, you should add mapper.

To add a mapper, you call addMapper() method to add single mapper or call mappers() method to send multiple mappers with array

First parameter of addMapper() method is parameter name and second parameter is relation name and its field name, which separate by " . " sign

$mappers = [
    'country' => 'country.name',
];

For example we want to sort Book entity by its Country name. Book has ManyToOne relation with Country entity

/*
 * Sort book by Country name ascending
*/
//Get api/book/index?order[country]=ASC
OR
$orders = [
    'country' => SortType::ASC,
];

/*
 * Sort book by Country name descending
*/
//Get api/book/index?order[country]=DESC
OR
$orders = [
    'country' => SortType::DESC,
];

The following code is in Book controller.

public function index(
    Request $request,
    BookRepository $bookRepository,
    QuerySorting $querySorting
): Response {
    $queryBuilder = $bookRepository->createQueryBuilder('b');
    
    $queryBuilder = $querySorting->for($queryBuilder)
        ->parameters($request->get('order'))
        ->addMapper('country', 'country.name')
        ->sort()
    ;
    
    return $queryBuilder->getQuery()->getResult();
}

NOTE: There is no need to add your relationship join in Query builder because if join is not added, I will add it automatically. ;)

$queryBuilder = $bookRepository->createQueryBuilder('b');

OR

$queryBuilder = $bookRepository->createQueryBuilder('b')
    ->addSelect('country')   
    ->leftJoin('b.country', 'country')      
;

If you want to sort the ManyToMany relation field or two level deep relation, you should again add mapper

$mapper = [
    'age' => 'bookUsers.user.age',
];

For example we want to sort Book entity by its Writer age. Book has ManyToMany relation with User entity

/*
 * Sort book by Writer age ascending
*/
//Get api/book/index?order[age]=ASC
OR
$orders = [
    'age' => SortType::ASC,
];

/*
 * Sort book by Writer age descending
*/
//Get api/book/index?order[age]=DESC
OR
$orders = [
    'age' => SortType::DESC,
];

The following code is in Book controller.

public function index(
    Request $request,
    BookRepository $bookRepository,
    QuerySorting $querySorting
): Response {
    $queryBuilder = $bookRepository->createQueryBuilder('b');
    
    $queryBuilder = $querySorting->for($queryBuilder)
        ->parameters($request->get('order'))
        ->addMapper('age', 'bookUsers.user.age')
        ->sort()
    ;
    
    return $queryBuilder->getQuery()->getResult();
}

NOTE: You should know that you can sort data with multiple columns too, you just need to send multiple order data with a Query string like this:

/*
 * Sort book by title ascending and price descending
*/
//Get api/book/index?order[title]=ASC&order[price]=DESC
OR
$orders = [
    'title' => SortType::ASC,
    'price' => SortType::DESC,
];

Suggestion

You can change two parameters with the config file, just make a yaml file in config/packages/ directory then you can change default cache time for queries and default relation separator as follows:

query_sorting:
  default_cache_time: 3600
  separator: '.'

NOTE: You can set the cache time for each query separately and if you don't set any cache time, it uses default cache time in your config file

$queryBuilder = $querySorting->for($queryBuilder)
    ->parameters($request->get('order'))
    ->cacheTime(120)
    ->sort()
;

Contributing v beer

If you find an issue, or have a better way to do something, feel free to open an issue or a pull request.

You might also like...
Small script for importing the KvK (Dutch Chamber of Commerce) Open Data Set (CSV file) to a MySQL database.
Small script for importing the KvK (Dutch Chamber of Commerce) Open Data Set (CSV file) to a MySQL database.

KvK-CSV-2-SQL Small script for importing the KvK (Dutch Chamber of Commerce) Open Data Set (CSV file) to a MySQL database. Table of content KvK-CSV-2-

Easy data transfer from one database to another

Migrate DB Easy data transfer from one database to another Installation To get the latest version of Migrate DB, simply require the project using Comp

A lightweight nearly-zero-configuration object-relational mapper and fluent query builder for PHP5.

Idiorm http://j4mie.github.com/idiormandparis/ Feature/API complete Idiorm is now considered to be feature complete as of version 1.5.0. Whilst it wil

Independent query builders for MySQL, PostgreSQL, SQLite, and Microsoft SQL Server.

Aura.SqlQuery Provides query builders for MySQL, Postgres, SQLite, and Microsoft SQL Server. These builders are independent of any particular database

A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)

Laravel MongoDB This package adds functionalities to the Eloquent model and Query builder for MongoDB, using the original Laravel API. This library ex

A Redis bundle for Symfony supporting Predis and PhpRedis

RedisBundle About This bundle integrates Predis and PhpRedis into your Symfony 3.4+ application, providing a fast and convenient interface to Redis. U

A SQL query builder with zero dependencies

Latitude Query Builder A SQL query builder with zero dependencies. Attempts to be PSR-1, PSR-2, and PSR-4 compliant. Install composer require latitude

SQL to Laravel Query Builder

Marwan - SQL To Laravel Builder SQL to Laravel Query Builder, A Converter written in PHP Features Converts SQL Queries to Laravel Query Builder. Assis

Get MYSQL statement from query builder in laravel helper

Get MYSQL statement laravel This package allows to get mysql statement that query builder in laravel made it for debugging purposes. Basic usage Dump

Releases(v1.0.4)
Owner
Bugloos
A web development agency specialized in online software. With more than 15 years of experience in creating customized web solutions
Bugloos
MOP is a php query handling and manipulation library providing easy and reliable way to manipulate query and get result in a fastest way. ( WEBSITE VERSION )

Mysql Optimizer mysql optimizer also known as MOP is a php query handling and manipulation library providing easy and reliable way to manipulate query

null 3 Feb 14, 2022
A simple program to query mysql data and display the queried data in JSON format

A simple program to query mysql data and display the queried data in JSON format. The data displayed in JSON format will change and update as the data in your mysql database changes.

null 2 Mar 7, 2022
Connect and work with MySQL/MariaDB database through MySQLi in PHP. This is an introductory project, If you need a simple and straightforward example that takes you straight to the point, you can check out these examples.

First MySQLi PHP Connect and work with MySQL/MariaDB database through MySQLi in PHP. The above exercises are designed for students. This is an introdu

Max Base 4 Feb 22, 2022
📐 Symfony Bundle to generate database diagrams

Doctrine Diagram Bundle ?? Symfony Bundle to generate database diagrams.

Jawira Portugal 10 Jan 8, 2023
Database Abstraction Layer, Schema Introspection, Schema Generation, Query Builders

Cycle DBAL Secure, multiple SQL dialects (MySQL, PostgreSQL, SQLite, SQLServer), schema introspection, schema declaration, smart identifier wrappers,

Cycle ORM 30 Oct 18, 2022
Eloquent Filter is a package for filter data of models by the query strings. Easy to use and fully dynamic.

Eloquent Filter Eloquent Filter adds custom filters to your Eloquent Models in Laravel. It's easy to use and fully dynamic. Table of Content Introduct

Mehdi Fathi 327 Dec 28, 2022
A drop-in library for certain database functionality in Laravel, that allows for extra features that may never make it into the main project.

Eloquence Eloquence is a package to extend Laravel's base Eloquent models and functionality. It provides a number of utilities and classes to work wit

Kirk Bushell 470 Dec 8, 2022
SleekwareDB is a NoSQL database storage service. A database storage service that can be used for various platforms and is easy to integrate.

SleekwareDB is a NoSQL database storage service. A database storage service that can be used for various platforms and is easy to integrate. NoSQL API

SleekwareDB 12 Dec 11, 2022
Pure PHP NoSQL database with no dependency. Flat file, JSON based document database.

Please give it a Star if you like the project ?? ❤️ SleekDB - A NoSQL Database made using PHP Full documentation: https://sleekdb.github.io/ SleekDB i

Kazi Mehedi Hasan 745 Jan 7, 2023
Database adapter for data interfaces

Yii _____ The package ... Requirements PHP 7.4 or higher. Installation The package could be installed with composer: composer require yiisoft/_____ --

Yii Software 8 Oct 15, 2022