Answer the question
In order to leave comments, you need to log in
How to convert SQL query to ActiveRecord?
Good night... Sitting for the fifth hour, I can't understand why activerecord distorts my sql query.
Ideally, this query should be transferred to activerecord:
select
user.id,
user_field.name,
user_field_value.value
from `user`
join `user_field` on user.site_id=user_field.site_id
left join `user_field_value` on user_field.id=user_field_value.field_id
and user_field_value.user_id=user.id
where user.site_id=14 and user.id=139
public function getFields()
{
return $this->hasMany(UserField::className(), ['id' => 'field_id'])
->viaTable(UserFieldValue::tableName(), ['user_id' => 'id']);
}
SELECT
`user`.`id`,
`user_field`.`name`,
`user_field_value`.`value`
FROM `user`
LEFT JOIN `user_field_value` ON `user`.`id` = `user_field_value`.`user_id`
LEFT JOIN `user_field` ON `user_field_value`.`field_id` = `user_field`.`id`
WHERE `user`.`id`=139
$models = $siteModel->getUser()->all();
if( ! $models ) {
throw new NotFoundHttpException(Yii::t('users', 'Users is not found'));
}
$result = [];
foreach($models as $model) {
$s = $model->getFields();
var_dump($s->all(), $s->createCommand()->getRawSql());
break;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question