V
V
Victor Serobaba2016-12-08 02:22:56
MySQL
Victor Serobaba, 2016-12-08 02:22:56

How to bind aliases to tables in YII2?

I can't create a valid query due to the fact that the alias is not bound in Yii2.
I have a model:

class OrdersModel extends \app\components\MyActiveRecord
{
....
    public function getManager()
    {
        return $this->hasOne(UsersModel::className(), ['id' => 'user_id']);
    }
....
}

The bottom line: you need to get a bunch of managers from the user table (only managers)
I create a query
           $managers=self::find()->joinWith('manager')
                        ->where("manager.role='manager' ")
                        ->groupBy('user_id')
                        ->orderBy('manager.first_name, manager.last_name')
                       ->all();

I receive the following request with an error:
SELECT `aus_orders`.* FROM `aus_orders` LEFT JOIN `aus_users` ON `aus_orders`.`user_id` = `aus_users`.`id` WHERE manager.role='manager' GROUP BY `user_id` ORDER BY `manager`.`first_name`, `manager`.`last_name`

It is clearly visible that aliases are excluded during query assembly.
How to do it right to get a normal query with an alias for a table?
To generate something like this:
SELECT `aus_orders`.* ,manager * FROM `aus_orders` AS `manager` LEFT JOIN `aus_users` ON `aus_orders`.`user_id` = `manager`.`id` WHERE manager.role='manager' GROUP BY `user_id` ORDER BY `manager`.`first_name`, `manager`.`last_name`

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2016-12-08
@vikweb

If you need to use a similar alias for communication everywhere, then in the model you can do this:

public function getManager()
{
    return $this->hasOne(UsersModel::className(), ['id' => 'user_id'])->alias('manager');
}

If you only need an alias in one place, but not in the rest, you can do this:
$managers = self::find()
    ->joinWith([
        'manager' => function($query) {
            $query->alias('manager'); 
        }
    ])
    ->where("manager.role='manager' ")
    ->groupBy('user_id')
    ->orderBy('manager.first_name, manager.last_name')
    ->all();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question