PHPackages                             mbohuslavek/leanmapper-query - 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. mbohuslavek/leanmapper-query

ActiveLibrary[Database &amp; ORM](/categories/database)

mbohuslavek/leanmapper-query
============================

Concept of Query Object for LeanMapper

v1.4.1(7mo ago)1011.9k↓50%7[1 issues](https://github.com/mibk/LeanMapperQuery/issues)2MITPHPPHP ^7.4 || ^8.0CI passing

Since Dec 29Pushed 7mo ago4 watchersCompare

[ Source](https://github.com/mibk/LeanMapperQuery)[ Packagist](https://packagist.org/packages/mbohuslavek/leanmapper-query)[ RSS](/packages/mbohuslavek-leanmapper-query/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (7)Dependencies (3)Versions (17)Used By (2)

Lean Mapper Query
=================

[](#lean-mapper-query)

Lean Mapper Query is a concept of a *query object* for [Lean Mapper library](https://github.com/Tharos/LeanMapper) which helps to build complex queries using automatic joins (*idea taken from [NotORM library](https://www.notorm.com/)*). Look at the [suggested base classes](https://gist.github.com/mibk/9410266). For Czech documentation have a look at the [wiki](https://github.com/mibk/LeanMapperQuery/wiki).

Features
--------

[](#features)

- behaves as a `SQL` preprocessor, hence most SQL expressions are available
- automatic joins using the *dot notation* (`@book.tags.name`)
- ability to query repositories or entities
- support for implicit filters

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

[](#installation)

It can be installed via [Composer](https://getcomposer.org/download).

```
composer require mbohuslavek/leanmapper-query

```

What does it do?
----------------

[](#what-does-it-do)

Suppose we have the following repositories:

```
class BaseRepository extends LeanMapper\Repository
{
	public function find(Query $query)
	{
		$this->createEntities($query
			->applyQuery($this->createFluent(), $this->mapper)
			->fetchAll()
		);
	}
}

class BookRepository extends BaseRepository
{
}
```

and the following entities:

```
/**
 * @property int    $id
 * @property string $name
 */
class Tag extends LeanMapper\Entity
{
}

/**
 * @property int      $id
 * @property Author   $author m:hasOne
 * @property Tag[]    $tags m:hasMany
 * @property DateTime $pubdate
 * @property string   $name
 * @property bool     $available
 */
class Book extends LeanMapper\Entity
{
}

/**
 * @property int    $id
 * @property string $name
 * @property Book[] $books m:belongsToMany
 */
class Author extends LeanMapper\Entity
{
}
```

We build a *query*:

```
$query = new LeanMapperQuery\Query;
$query->where('@author.name', 'Karel');
```

Now, if we want to get all books whose author's name is Karel, we have to do this:

```
$bookRepository = new BookRepository(...);
$books = $bookRepository->find($query);
```

The database query will look like this:

```
SELECT [book].*
FROM [book]
LEFT JOIN [author] ON [book].[author_id] = [author].[id]
WHERE ([author].[name] = 'Karel')
```

You can see it performs automatic joins via the *dot notation*. It supports all relationship types known to **Lean Mapper**.

It is very easy to use SQL functions. We can update query like this:

```
$query->where('DATE(@pubdate) > %d', '1998-01-01');
$books = $bookRepository->find($query);
```

which changes the database query into the following:

```
SELECT [book].*
FROM [book]
LEFT JOIN [author] ON [book].[author_id] = [author].[id]
WHERE ([author].[name] = 'Karel') AND (DATE([book].[pubdate]) > '1998-01-01')
```

Don't repeat yourself
---------------------

[](#dont-repeat-yourself)

You can extend the `Query` class and define your own methods.

```
class BookQuery extends LeanMapperQuery\Query
{
	public function restrictAvailable()
	{
		$this->where('@available', true)
			->orderBy('@author.name');
		return $this;
	}
}

/////////

$query = new BookQuery;
$query->restrictAvailable();
$books = $this->bookRepository->find($query);
```

Querying entities
-----------------

[](#querying-entities)

It is also possible to query an entity property (*currently only those properties with `BelongsToMany` or `HasMany` relationships*). Let's make the `BaseEntity` class:

```
class BaseEntity extends LeanMapperQuery\Entity
{
	protected static $magicMethodsPrefixes = ['find'];

	protected function find($field, Query $query)
	{
		$entities = $this->queryProperty($field, $query);
		return $this->entityFactory->createCollection($entities);
	}
}

/*
 * ...
 */
class Book extends BaseEntity
{
}
```

*Note that `BaseEntity` must extend `LeanMapperQuery\Entity` to make the following possible.*

We have defined the `find` method as `protected` because by specifying the method name in the `$magicMethodsPrefixes` property, you can query entities like this:

```
$book; // previously fetched instance of an entity from a repository
$query = new LeanMapper\Query;
$query->where('@name !=', 'ebook');
$tags = $book->findTags($query);
```

*The magic method `findTags` will eventually call your protected method `find` with 'tags' as the 1st argument.*

The resulting database query looks like this:

```
SELECT [tag].*
FROM [tag]
WHERE [tag].[id] IN (1, 2) AND ([tag].[name] != 'ebook')
```

The first condition in the `where` clause, `[tag].[id] IN (1, 2)`, is taken from the entity traversing (*tags are queried against this particular book entity's own tags*).

What else you can do?
---------------------

[](#what-else-you-can-do)

If we slightly modify `BaseRepository` and `BaseEntity`, we can simplify working with query objects. *To achieve this look at the [suggested base classes](https://gist.github.com/mibk/9410266)*. It makes the following possible.

```
$books = $bookRepository->query()
	->where('@author.name', 'Karel')
	->where('DATE(@pubdate) > ?', '1998-01-01')
	->find();

// or...

$tags = $book->queryTags()
	->where('@name !=', 'ebook')
	->find();
```

License
-------

[](#license)

Copyright (c) 2013 Michal Bohuslávek

Licensed under the MIT license.

###  Health Score

51

—

FairBetter than 96% of packages

Maintenance64

Regular maintenance activity

Popularity32

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity76

Established project with proven stability

 Bus Factor1

Top contributor holds 76% 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 ~427 days

Recently: every ~581 days

Total

11

Last Release

236d ago

Major Versions

v0.9.0 → v1.0.02017-02-16

PHP version history (4 changes)v1.0.0PHP &gt;=5.3.0

v1.1.0PHP &gt;=5.4.0

v1.2.0PHP ^7.1 || ^8.0

v1.3.0PHP ^7.4 || ^8.0

### Community

Maintainers

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

---

Top Contributors

[![mibk](https://avatars.githubusercontent.com/u/2324898?v=4)](https://github.com/mibk "mibk (92 commits)")[![janpecha](https://avatars.githubusercontent.com/u/637719?v=4)](https://github.com/janpecha "janpecha (25 commits)")[![lSimul](https://avatars.githubusercontent.com/u/55706364?v=4)](https://github.com/lSimul "lSimul (4 commits)")

---

Tags

databaseleanmapperphpphp-library

###  Code Quality

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/mbohuslavek-leanmapper-query/health.svg)

```
[![Health](https://phpackages.com/badges/mbohuslavek-leanmapper-query/health.svg)](https://phpackages.com/packages/mbohuslavek-leanmapper-query)
```

###  Alternatives

[doctrine/orm

Object-Relational-Mapper for PHP

10.2k285.3M6.2k](/packages/doctrine-orm)[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k115.1M102](/packages/jdorn-sql-formatter)[illuminate/database

The Illuminate Database package.

2.8k52.4M9.3k](/packages/illuminate-database)[mongodb/mongodb

MongoDB driver library

1.6k64.0M542](/packages/mongodb-mongodb)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

90340.3M209](/packages/ramsey-uuid-doctrine)[reliese/laravel

Reliese Components for Laravel Framework code generation.

1.7k3.4M16](/packages/reliese-laravel)

PHPackages © 2026

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