PHP code example of yii2tech / ar-eagerjoin
1. Go to this page and download the library: Download yii2tech/ar-eagerjoin library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once ('vendor/autoload.php' );
yii2tech / ar-eagerjoin example snippets
$items = Item::find()
->joinWith('group' )
->orderBy(['{{group}}.[[name]]' => SORT_ASC])
->all();
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' ]);
}
}
$items = Item::find()
->select(['Item.*' , 'group__name' => 'Group.name' , 'group__code' => 'Group.code' ])
->joinWith('group' , false )
->all();
foreach ($items as $item) {
var_dump($item->isRelationPopulated('group' ));
echo $item->group->name;
echo $item->group->code;
echo get_class($item->group);
}
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 ;
public static function find ()
{
return new ItemQuery(get_called_class());
}
}
$items = Item::find()->eagerJoinWith('group' )->all();