2017 © Pedro Peláez
 

yii2-extension ar-eagerjoin

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

image

yii2tech/ar-eagerjoin

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

  • Thursday, July 27, 2017
  • by klimov-paul
  • Repository
  • 3 Watchers
  • 21 Stars
  • 1,386 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 3 Versions
  • 6 % Grown

The README.md

, (*1)

ActiveRecord Eager Join Extension for Yii 2


This extension provides support for ActiveRecord relation eager loading via 'join' without extra query., (*2)

For license information check the LICENSE-file., (*3)

Latest Stable Version Total Downloads Build Status, (*4)

Installation

The preferred way to install this extension is through composer., (*5)

Either run, (*6)

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

or add, (*7)

"yii2tech/ar-eagerjoin": "*"

to the require section of your composer.json., (*8)

Usage

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

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:, (*10)

$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., (*11)

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

Setup example:, (*13)

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:, (*14)

{relationName}{boundary}{columnName}

where:, (*15)

  • '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:, (*16)

$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., (*17)

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

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., (*19)

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., (*20)

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:, (*21)

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:, (*22)

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

Composition of the proper 'select' and 'join' statements will be performed automatically., (*23)

Restrictions and drawbacks

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

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., (*25)

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., (*26)

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., (*27)

The Versions

27/07 2017

dev-master

9999999-dev

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

  Sources   Download

BSD-3-Clause

The Requires

 

by Paul Klimov

yii2 active record relation eager join together

08/12 2016

1.0.1

1.0.1.0

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

  Sources   Download

BSD-3-Clause

The Requires

 

by Paul Klimov

yii2 active record relation eager join together

10/02 2016

1.0.0

1.0.0.0

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

  Sources   Download

BSD-3-Clause

The Requires

 

by Paul Klimov

yii2 active record relation eager join