PHPackages                             yii2tech/ar-eagerjoin - 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. yii2tech/ar-eagerjoin

AbandonedArchivedYii2-extension[Database &amp; ORM](/categories/database)

yii2tech/ar-eagerjoin
=====================

Provides support for ActiveRecord relation eager loading via join without extra query in Yii2

1.0.2(7y ago)2418.8k↓43.8%3BSD-3-ClausePHP

Since Feb 10Pushed 6y ago3 watchersCompare

[ Source](https://github.com/yii2tech/ar-eagerjoin)[ Packagist](https://packagist.org/packages/yii2tech/ar-eagerjoin)[ RSS](/packages/yii2tech-ar-eagerjoin/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (1)Versions (4)Used By (0)

 [ ![](https://avatars2.githubusercontent.com/u/12951949) ](https://github.com/yii2tech)

ActiveRecord Eager Join Extension for Yii 2
===========================================

[](#activerecord-eager-join-extension-for-yii-2)

This extension provides support for ActiveRecord relation eager loading via 'join' without extra query.

For license information check the [LICENSE](LICENSE.md)-file.

[![Latest Stable Version](https://camo.githubusercontent.com/3a5d6b3976cb3e6d2b147d46f862713b752bd8531c1bfb76b5dc1314dd230d72/68747470733a2f2f706f7365722e707567782e6f72672f79696932746563682f61722d65616765726a6f696e2f762f737461626c652e706e67)](https://packagist.org/packages/yii2tech/ar-eagerjoin)[![Total Downloads](https://camo.githubusercontent.com/58876c1dec71c294feeb7691c749d816581ac3202181e8cf1b19fe8710fde1b9/68747470733a2f2f706f7365722e707567782e6f72672f79696932746563682f61722d65616765726a6f696e2f646f776e6c6f6164732e706e67)](https://packagist.org/packages/yii2tech/ar-eagerjoin)[![Build Status](https://camo.githubusercontent.com/4a3f39e601a9c71ed821e9062e684a5a1b288cbd7f8d882c4413ac12120df0fd/68747470733a2f2f7472617669732d63692e6f72672f79696932746563682f61722d65616765726a6f696e2e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/yii2tech/ar-eagerjoin)

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

[](#installation)

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

Either run

```
php composer.phar require --prefer-dist yii2tech/ar-eagerjoin

```

or add

```
"yii2tech/ar-eagerjoin": "*"
```

to the require section of your composer.json.

Usage
-----

[](#usage)

This extension provides support for ActiveRecord relation eager loading via 'join' without extra query. Imagine we have the following database structure:

```
CREATE TABLE `Group`
(
   `id` integer NOT NULL AUTO_INCREMENT,
   `name` varchar(64) NOT NULL,
   `code` varchar(10) NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE InnoDB;

CREATE TABLE `Item`
(
   `id` integer NOT NULL AUTO_INCREMENT,
   `groupId` integer NOT NULL,
   `name` varchar(64) NOT NULL,
   `price` float,
    PRIMARY KEY (`id`)
    FOREIGN KEY (`groupId`) REFERENCES `Group` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
) ENGINE InnoDB;
```

If you need to display listing of items, with the groups they belong to, ordered by group name or code, you'll have to use `JOIN` SQL statement and thus - `\yii\db\ActiveQuery::joinWith()` method:

```
$items = Item::find()
    ->joinWith('group')
    ->orderBy(['{{group}}.[[name]]' => SORT_ASC])
    ->all();
```

However, the code above will perform 2 SQL queries: one - for the item fetching (including `JOIN` and `ORDER BY` statements) and second - for the group fetching. While second query will be very simple and fast, it is still redundant and unefficient, since all group columns may be selected along with the item ones.

This extension provides \[\[yii2tech\\ar\\eagerjoin\\EagerJoinTrait\]\] trait, which, once used in the ActiveRecord class, allows selecting related records without extra SQL query.

Setup example:

```
use yii\db\ActiveRecord;
use yii2tech\ar\eagerjoin\EagerJoinTrait;

class Item extends ActiveRecord
{
    use EagerJoinTrait;

    public function getGroup()
    {
        return $this->hasOne(Group::className(), ['id' => 'groupId']);
    }
}
```

In order to populate related record though 'join' query, you'll need to manually append its columns into the `SELECT` query section and alias them by names in following format:

```
{relationName}{boundary}{columnName}

```

where:

- 'relationName' - name of the relation to be populated
- 'columnName' - name of the column(attribute) of the related record to be filled
- 'boundary' - separator configured by \[\[yii2tech\\ar\\eagerjoin\\EagerJoinTrait::eagerJoinBoundary()\]\]

For example:

```
$items = Item::find()
    ->select(['Item.*', 'group__name' => 'Group.name', 'group__code' => 'Group.code'])
    ->joinWith('group', false) // disable regular eager loading!!!
    ->all();

foreach ($items as $item) {
    var_dump($item->isRelationPopulated('group')); // outputs `true`!!!
    echo $item->group->name; // no extra query performed!
    echo $item->group->code; // no extra query performed!
    echo get_class($item->group); // outputs 'Group'!
}
```

Here 'group\_\_name' column of the query result set is passed to `$item->group->name`, 'group\_\_code' - to `$item->group->code` and so on.

**Heads up!** Do not forget to disable eager loading, passing `false` as second argument of `joinWith()`method, otherwise you'll gain no benefit.

> Note: choose `boundary` carefully: it should not be present as a part of the columns (or aliases), which are not meant to be passed to the related records. Thus double underscore ('\_\_') is used as default.

> Tip: if you use 'camelCase' notation for your table columns, you may use single underscore ('\_') as a boundary in order to make select statements more clear.

You may speed up composition of the query for the eager join using \[\[\\yii2tech\\ar\\eagerjoin\\EagerJoinQueryTrait\]\] trait. This trait should be used in the \[\[\\yii\\db\\ActiveQuery\]\] instance:

```
use yii\db\ActiveQuery;
use yii2tech\ar\eagerjoin\EagerJoinQueryTrait;
use yii\db\ActiveRecord;
use yii2tech\ar\eagerjoin\EagerJoinTrait;

class ItemQuery extends ActiveQuery
{
    use EagerJoinQueryTrait;

    // ...
}

class Item extends ActiveRecord
{
    use EagerJoinTrait;

    /**
     * @inheritdoc
     * @return ItemQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new ItemQuery(get_called_class());
    }

    // ...
}
```

Then you'll be able to use `eagerJoinWith()` method while building a query:

```
$items = Item::find()->eagerJoinWith('group')->all();
```

Composition of the proper 'select' and 'join' statements will be performed automatically.

Restrictions and drawbacks
---------------------------

[](#restrictions-and-drawbacks-)

While reducing the number of executed queries, this extension has several restrictions and drawbacks.

1. Only 'has-one' relations are supported. Extension is unable to handle 'has-many' relations. You should use regular `joinWith()` and eager loading for 'has-many' relations.
2. If all selected related model fields will be `null`, the whole related record will be set to `null`. You should always select at least one 'not null' column to avoid inappropriate results.
3. Despite extra query removal, this extension may not actually increase overall performance. Regular Yii eager join query is very simple and fast, while this extension consumes extra memory and performs extra calculations. Thus in result performance remain almost the same. In most cases usage of this extension is a tradeoff: it reduces load on Database side, while increases it on PHP side.

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity35

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor1

Top contributor holds 96.9% 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 ~539 days

Total

3

Last Release

2671d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/854af1889dd7384243cff0bf0fde23463f76058b499b15c740f02e7033ec7ce6?d=identicon)[klimov-paul](/maintainers/klimov-paul)

---

Top Contributors

[![klimov-paul](https://avatars.githubusercontent.com/u/1482054?v=4)](https://github.com/klimov-paul "klimov-paul (31 commits)")[![urusaich](https://avatars.githubusercontent.com/u/13536462?v=4)](https://github.com/urusaich "urusaich (1 commits)")

---

Tags

activerecordeager-loadingjoinyiiyii2yii2-extensionjoinrecordyii2activerelationeagertogether

### Embed Badge

![Health badge](/badges/yii2tech-ar-eagerjoin/health.svg)

```
[![Health](https://phpackages.com/badges/yii2tech-ar-eagerjoin/health.svg)](https://phpackages.com/packages/yii2tech-ar-eagerjoin)
```

###  Alternatives

[mootensai/yii2-relation-trait

Yii 2 Models load with relation, &amp; transaction save with relation

47220.3k9](/packages/mootensai-yii2-relation-trait)

PHPackages © 2026

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