Many to many relaton and inverseOf

Hi there. Does AR supports inverseOf for many to many relations?

I have 2 tables related by third one like:

class TemplateType extends ActiveRecord


    public function getSites()


        return $this->hasMany(Site::className(), ['id' => 'siteId'])

            ->viaTable('SiteToTemplateType', ['templateTypeId' => 'id'])->inverseOf('templateTypes');



class Site extends ActiveRecord


    public function getTemplateTypes()


        return $this->hasMany(TemplateType::className(), ['id' => 'templateTypeId'])

            ->viaTable('SiteToTemplateType', ['siteId' => 'id'])->inverseOf('sites');



Then, when i’m trying to get :

$templateType = TemplateType::find()->where(['id' => 5])->with('sites')->one();

it tells me error:

Getting unknown property: app\models\records\Site::templateTypeId

It’s like trying to relate them by field in Site class, not in relational table named SiteToTemplateType.

Thanks in advance.

Hi, welcome to the forum.

Unfortunately, the guide clearly says "No" to your question.

Guide > Active Record > Inverse Relations

Thank’s for answer. Didn’t saw that notice. Are you planning to make inverseOf for relations involving a junction table? If not, what’s reason for not making it?

I’m not a developer of the framework, so the following is only a humble opinion of mine.

IMO, "inverseOf" has a very limited range of use cases.

It may be useful for "hasMany" relation where the inverse of it is just one model instance. But the inverse of "hasOne", which can be many instances, is not very easy to use.

Please read the description of the API for the detail:

A has_many relation via junction table can be divided to a pair of has_many and has_one relations.

For example, a TemplateType has many TemplateTypeToSites and a TemplateTypeToSite has one Site.

Since you can define "inverseOf"s for those 2 simple relations, you would be able to make use of the "inverseOf" feature using this pair of the relations.

But I’m afraid it’s not very easy to use nor very useful.