Answer the question
In order to leave comments, you need to log in
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']);
}
....
}
$managers=self::find()->joinWith('manager')
->where("manager.role='manager' ")
->groupBy('user_id')
->orderBy('manager.first_name, manager.last_name')
->all();
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`
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
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');
}
$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 questionAsk a Question
731 491 924 answers to any question