M
M
Makar Gerasimov2016-10-31 03:27:18
Yii
Makar Gerasimov, 2016-10-31 03:27:18

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

But I got it like this, and it doesn't work:
public function getFields()
{
        
    return $this->hasMany(UserField::className(), ['id' => 'field_id'])
            ->viaTable(UserFieldValue::tableName(), ['user_id' => 'id']);
}

As a result, it will collect the following:
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

If this is executed in the console, the table will be formed and give the values ​​of custom fields for the specified user.
But if, for example, you call it like this:
$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;
        }

Will output everything except user_field_value.
How to be? My brain is already exploding

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2016-10-31
@slo_nik

Goodnight.
Can you specify a request with a link?

$models = $siteModel->getUser()->with('fields')->all();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question