ActiveRecord | select only returning the model columns instead of model & additional columns

I have the following code where I try to return all the model attribute plus relation attributes:

User::find()
                ->joinWith("document user_doc")
                ->joinWith("document user_doc")
                ->select([User::tableName() . ".*", "user_doc.image as profile_picture", "user_doc.image as driver_license"])
                ->where(['sate_id' => $id, 'user_doc.type' => 'profile_picture', 'user_doc.type' => 'driver_license'])
                ->all();

In the select, I try to bring all user model attributes and 2 attributes coming from the relation. The sql sentence is ok and from mariadb I can get what I need but not else in Yii2, because Yii2 only returns the model attributes.

If I try to run as query command, the sql sentence won’t be well formed, for instance, "{{%user}}.id" => "profile_pic.id_user" will be printed as

`user`.`id` = 'user_doc.id_user'

So, the sentence is trying to compare an integer field with a literal ‘user_doc.id_user’ instead with the field id_user from the alias table user_doc.

How can I to bring both, the model attributes and the relation attributes?

You would need to add those extra attributes into your User class. You could also extend it and create a class just for the purpose of that search.

For example, create a class called UserWithDocuments that extends form User and add those extra attributes there.

Another way of doing it is creating a direct query:

$query = (new \yii\db\Query())->select(...)->all();

This would retrieve an array, though, so you need to review which is best for your case.

Also, another thing: you don’t need to call joinWith twice as you are calling right there, maybe each one had to have a different name?

Uhm yeah, I didn’t want to use the Query class but I see it is the only option.

Because an error where I was composing the post I put twice the joinWith, but actually I don’t do it.

Thank you.