Yii2 - hasMany with custom query

I am trying to create custom query in the hasMany function. I am not getting any error, but I am not getting any data from the table inside join statement. What’s is wrong?

This is the function:

return $this->hasMany(UserKeys::classname(), ['user_id' => 'id'])

                ->select('licences.licenceName, userKeys.*')


                ->innerJoin('licences', 'licences.id = userKeys.licence_id');

Does UserKey has one License?

Probably you are trying to optimize the nested relations into a single one.

Something has many Userkeys, and UserKey has one License … you thought that combining these 2 into 1 would be nice, didn’t you?

In short, don’t do it.

It’s better to leave them as they are now.

You should be able to write like the following:

$q = Something::find()->with(['userKey', 'userKey.license'])->...

This should work as expected, and there’s no performance drawback in it.


The query you have defined for the relation should work as expected, but Yii will not use ‘licences.licenceName’ to populate the related ‘UserKeys’ model.