PHPackages                             icings/partitionable - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. icings/partitionable

ActiveCakephp-plugin[Database &amp; ORM](/categories/database)

icings/partitionable
====================

Partitionable associations for the CakePHP ORM, allowing for basic limiting per group.

2.0.1(1y ago)157.3k↑63.1%3[1 PRs](https://github.com/icings/partitionable/pulls)MITPHPPHP &gt;=8.1CI failing

Since May 31Pushed 1y ago2 watchersCompare

[ Source](https://github.com/icings/partitionable)[ Packagist](https://packagist.org/packages/icings/partitionable)[ RSS](/packages/icings-partitionable/feed)WikiDiscussions 2.x Synced 1mo ago

READMEChangelog (7)Dependencies (4)Versions (9)Used By (0)

Partitionable
=============

[](#partitionable)

[![Build Status](https://camo.githubusercontent.com/800a7981c3d73e9110b97d6353614124df658faa4fccd676fc9f99e6d96eb54e/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6963696e67732f706172746974696f6e61626c652f63692e796d6c3f6272616e63683d322e78267374796c653d666c61742d737175617265)](https://github.com/icings/partitionable/actions/workflows/ci.yml?query=branch%3A2.x)[![Coverage Status](https://camo.githubusercontent.com/9dfea8a72858c8e05c95f11177f291793ae30302b7e67a2d6d9053c3ac091af7/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f6963696e67732f706172746974696f6e61626c652f322e782e7376673f7374796c653d666c61742d737175617265)](https://codecov.io/github/icings/partitionable/tree/2.x)[![Latest Version](https://camo.githubusercontent.com/827440e3dfc704a014bc58f0f520a761c8cd3c5ed2b3ab0c7ac1b33dfb4017d5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6963696e67732f706172746974696f6e61626c652e7376673f7374796c653d666c61742d737175617265266c6162656c3d6c6174657374)](https://packagist.org/packages/icings/partitionable)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.txt)

A set of partitionable associations for the CakePHP ORM, allowing for basic limiting per group.

Requirements
------------

[](#requirements)

- CakePHP ORM 5.0+ (use the [1.x branch](https://github.com/icings/partitionable/tree/1.x) of this plugin if you're looking for CakePHP 4 compatibility).
- A DBMS supported by CakePHP with window function support (MySQL 8, MariaDB 10.2, Postgres 9.4, SQL Sever 2017, Sqlite 3.25).

Installation
------------

[](#installation)

Use [Composer](https://getcomposer.org) to add the library to your project:

```
composer require icings/partitionable
```

I don't get it, what is this good for exactly?
----------------------------------------------

[](#i-dont-get-it-what-is-this-good-for-exactly)

What exactly are these associations good for, what is a "*limit per group*" you may ask.

Basically the associations provided in this library allow applying limits for `hasMany` and `belongsToMany` type of associations, so that it's possible to for example receive a maximum of *n* number of comments per article for an `Articles hasMany Comments` association.

Usage
-----

[](#usage)

**Make sure to first check the [Known Issues/Limitations](#known-issueslimitations) section!**

Then add the `\Icings\Partitionable\ORM\AssociationsTrait` trait to your table class, use its `partitionableHasMany()`and `partitionableBelongsToMany()` methods to add `hasMany`, respectively `belongsToMany` associations, configure a limit and a sort order, and you're done with the minimal setup and you can contain the partitionable associations just like any other associations.

Note that configuring a sort order is mandatory, as it is not possible to reliably partition the results without an explicit sort order, omitting it will result in an error!

### Has Many

[](#has-many)

```
// ...
use Icings\Partitionable\ORM\AssociationsTrait;

class ArticlesTable extends \Cake\ORM\Table
{
    use AssociationsTrait;

    public function initialize(array $config): void
    {
        // ...

        $this
            ->partitionableHasMany('TopComments')
            ->setClassName('Comments')
            ->setLimit(3)
            ->setSort([
                'TopComments.votes' => 'DESC',
                'TopComments.id' => 'ASC',
            ]);
    }
}
```

```
$articlesQuery = $this->Articles
    ->find()
    ->contain('TopComments');
```

That would query the 3 highest voted comments for each article, eg the result would look something like:

```
[
    'title' => 'Some Article',
    'top_comments' => [
        [
            'votes' => 10,
            'body' => 'Some Comment',
        ],
        [
            'votes' => 9,
            'body' => 'Some Other Comment',
        ],
        [
            'votes' => 8,
            'body' => 'And Yet Another Comment',
        ],
    ],
]
```

### Belongs To Many

[](#belongs-to-many)

```
// ...
use Icings\Partitionable\ORM\AssociationsTrait;

class StudentsTable extends \Cake\ORM\Table
{
    use AssociationsTrait;

    public function initialize(array $config): void
    {
        // ...

        $this
            ->partitionableBelongsToMany('TopGraduatedCourses')
            ->setClassName('Courses')
            ->setThrough('CourseMemberships')
            ->setLimit(3)
            ->setSort([
                'CourseMemberships.grade' => 'ASC',
                'CourseMemberships.id' => 'ASC',
            ])
            ->setConditions([
                'CourseMemberships.grade IS NOT' => null,
            ]);
    }
}
```

```
$studentsQuery = $this->Students
    ->find()
    ->contain('TopGraduatedCourses');
```

That would query the 3 highest graduated courses for each student, eg the result would look something like:

```
[
    'name' => 'Some Student',
    'top_graduated_courses' => [
        [
            'name' => 'Some Course',
            '_joinData' => [
                'grade' => 1,
            ],
        ],
        [
            'body' => 'Some Other Course',
            '_joinData' => [
                'grade' => 2,
            ],
        ],
        [
            'body' => 'And Yet Another Course',
            '_joinData' => [
                'grade' => 3,
            ],
        ],
    ],
]
```

### Using options to configure the associations

[](#using-options-to-configure-the-associations)

Additionally to the chained method call syntax, options as known from the built-in associations are supported too, specifically the following options are supported for both `partitionableHasMany()` as well as `partitionableBelongsToMany()`:

- `limit` (`int|null`)
- `singleResult` (`bool`)
- `filterStrategy` (`string`)

```
$this
    ->partitionableHasMany('TopComments', [
        'className' => 'Comments',
        'limit' => 1,
        'singleResult' => false,
        'filterStrategy' => \Icings\Partitionable\ORM\Association\PartitionableHasMany::FILTER_IN_SUBQUERY_TABLE,
        'sort' => [
          'TopComments.votes' => 'DESC',
          'TopComments.id' => 'ASC',
        ],
    ]);
```

### Changing settings on the fly

[](#changing-settings-on-the-fly)

The limit and the sort order can be applied/changed on the fly in the containment's query builder:

```
$articlesQuery = $this->Articles
    ->find()
    ->contain('TopComments', function (\Cake\ORM\Query\SelectQuery $query) {
        return $query
            ->limit(10)
            ->order([
                'TopComments.votes' => 'DESC',
                'TopComments.id' => 'ASC',
            ]);
    });
```

and via `Model.beforeFind`, where the partitionable fetcher query that needs to be modified, can be identified via the option `partitionableQueryType`, which would hold the value `fetcher`:

```
$this->Articles->TopComments
    ->getEventManager()
    ->on('Model.beforeFind', function ($event, \Cake\ORM\Query\SelectQuery $query, \ArrayObject $options) {
        if (($options['partitionableQueryType'] ?? null) === 'fetcher') {
            $query
              ->limit(10)
              ->order([
                  'TopComments.votes' => 'DESC',
                  'TopComments.id' => 'ASC',
              ]);
        }

        return $query;
    });
```

### Limiting to a single result

[](#limiting-to-a-single-result)

When setting the limit to `1`, the associations will automatically switch to using singular property names (if no property name has been set yet), and non-nested results.

For example, limiting this association to `1`:

```
$this
    ->partitionableHasMany('TopComments')
    ->setClassName('Comments')
    ->setLimit(1)
    ->setSort([
        'TopComments.votes' => 'DESC',
        'TopComments.id' => 'ASC',
    ]);
```

would return a result like this:

```
[
    'title' => 'Some Article',
    'top_comment' => [
        'votes' => 10,
        'body' => 'Some Comment',
    ],
]
```

while a limit of greater or equal to `2`, would return a result like this:

```
[
    'title' => 'Some Article',
    'top_comments' => [
        [
            'votes' => 10,
            'body' => 'Some Comment',
        ],
        [
            'votes' => 5,
            'body' => 'Some Other Comment',
        ],
    ],
]
```

This behavior can be disabled using the association's `disableSingleResult()` method, and likewise *enabled* using `enableSingleResult()`. Calling the latter will also cause the limit to be set to `1`. Furthermore, setting the limit to greater or equal to `2`, will automatically disable the single result mode.

With the single result mode disabled:

```
$this
    ->partitionableHasMany('TopComments')
    ->setClassName('Comments')
    ->setLimit(1)
    ->disableSingleResult()
    ->setSort([
        'TopComments.votes' => 'DESC',
        'TopComments.id' => 'ASC',
    ]);
```

a limit of `1` would return a result like this:

```
[
    'title' => 'Some Article',
    'top_comments' => [
        [
            'votes' => 10,
            'body' => 'Some Comment',
        ],
    ],
]
```

### Filter Strategies

[](#filter-strategies)

The associations currently provide a few different filter strategies that affect how the query that obtains the associated data is being filtered.

Not all queries are equal, while one strategy may work fine for one query, it might cause problems for another.

The strategy can be set using the association's `setFilterStrategy()` method:

```
use Icings\Partitionable\ORM\Association\PartitionableHasMany;

// ...

$this
    ->partitionableHasMany('TopComments')
    ->setClassName('Comments')
    ->setFilterStrategy(PartitionableHasMany::FILTER_IN_SUBQUERY_TABLE)
    ->setLimit(3)
    ->setSort([
        'TopComments.votes' => 'DESC',
        'TopComments.id' => 'ASC',
    ]);
```

Please refer to the API docs for SQL examples of how the different strategies work:

- [`\Icings\Partitionable\ORM\Association\Loader\PartitionableSelectLoader`](src/ORM/Association/Loader/PartitionableSelectLoader.php)
- [`\Icings\Partitionable\ORM\Association\Loader\PartitionableSelectWithPivotLoader`](src/ORM/Association/Loader/PartitionableSelectWithPivotLoader.php)

The currently available strategies are:

- `\Icings\Partitionable\ORM\Association\PartitionableAssociationInterface::FILTER_IN_SUBQUERY_CTE`
- `\Icings\Partitionable\ORM\Association\PartitionableAssociationInterface::FILTER_IN_SUBQUERY_JOIN`
- `\Icings\Partitionable\ORM\Association\PartitionableAssociationInterface::FILTER_IN_SUBQUERY_TABLE` (default)
- `\Icings\Partitionable\ORM\Association\PartitionableAssociationInterface::FILTER_INNER_JOIN_CTE`
- `\Icings\Partitionable\ORM\Association\PartitionableAssociationInterface::FILTER_INNER_JOIN_SUBQUERY`

Known Issues/Limitations
------------------------

[](#known-issueslimitations)

- These associations are ***not*** meant for save or delete operations, *only* for read operations!
- MySQL 5 is not supported as it doesn't support the required window functions used for row numbering. While it's possible to emulate the required row numbering, these constructs are rather fragile and there's way too many situations in which they will break, respectively silently produce wrong results.
- MariaDB &gt;= 11.0 can crash with the `FILTER_IN_SUBQUERY_CTE`, and the default `FILTER_IN_SUBQUERY_TABLE` strategy when using the translate behavior with `onlyTranslated` enabled (). It is strongly advised to use a different filter strategy when you find yourself with that version and translate behavior config constellation!
- Older MariaDB versions, when running in `ONLY_FULL_GROUP_BY` mode, erroneously require a `GROUP BY` clause to be present when using window functions like the one used for row numbering (). If you cannot use a version where that bug was fixed, you either have to disable `ONLY_FULL_GROUP_BY`, or add grouping to the association's query accordingly.
- SQL Server does not support common table expressions in subqueries, hence the `FILTER_IN_SUBQUERY_CTE` strategy cannot be used with it. In fact, it's also not possible to use custom common table expressions in the association's query with any other strategy, as it would result in the expression to be used in a subquery too, or nested in another common table expression, which also isn't supported.

###  Health Score

40

—

FairBetter than 88% of packages

Maintenance32

Infrequent updates — may be unmaintained

Popularity33

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity66

Established project with proven stability

 Bus Factor1

Top contributor holds 98.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~141 days

Recently: every ~73 days

Total

9

Last Release

675d ago

Major Versions

0.2.0 → 1.0.0-RC12023-07-31

1.0.0-RC1 → 2.0.0-RC12023-07-31

1.0.0 → 2.0.02023-09-13

PHP version history (2 changes)0.1.0PHP &gt;=7.2

2.0.0-RC1PHP &gt;=8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/f0a4de55b3128733c4c0250c70b241f3d7446dd18ce44060974507bce40b62ee?d=identicon)[ndm2](/maintainers/ndm2)

---

Top Contributors

[![ndm2](https://avatars.githubusercontent.com/u/5031606?v=4)](https://github.com/ndm2 "ndm2 (70 commits)")[![dereuromark](https://avatars.githubusercontent.com/u/39854?v=4)](https://github.com/dereuromark "dereuromark (1 commits)")

---

Tags

associationscakephpdatabasegreatest-n-per-grouplimitormdatabaseormcakephplimitassociationsgreatest-n-per-group

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/icings-partitionable/health.svg)

```
[![Health](https://phpackages.com/badges/icings-partitionable/health.svg)](https://phpackages.com/packages/icings-partitionable)
```

###  Alternatives

[josegonzalez/cakephp-upload

CakePHP plugin to handle file uploading sans ridiculous automagic

5451.3M9](/packages/josegonzalez-cakephp-upload)[muffin/trash

Adds soft delete support to CakePHP ORM tables.

851.3M11](/packages/muffin-trash)[muffin/webservice

Simplistic webservices for CakePHP

88191.0k13](/packages/muffin-webservice)[admad/cakephp-sequence

Sequence plugin for CakePHP to maintain ordered list of records

46489.9k6](/packages/admad-cakephp-sequence)[riesenia/cakephp-duplicatable

CakePHP ORM plugin for duplicating entities (including related entities)

51384.5k4](/packages/riesenia-cakephp-duplicatable)[muffin/slug

Slugging support for CakePHP ORM

38264.8k5](/packages/muffin-slug)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
