pivotModel() relationship issues


#1

Let’s say that we have User, Car, UserCar and Registration models.

User model:
cars () {
return this
.belongsToMany(‘App/Models/Car’)
.pivotModel(‘App/Models/UserCar’)
}

Car model:
users () {
return this
.belongsToMany(‘App/Models/User’)
.pivotModel(‘App/Models/UserCar’)
}

UserCar (regular Lucid model):
user () {
return this.belongsTo(‘App/Models/User’)
}
car () {
return this.belongsTo(‘App/Models/Car’)
}
registration () {
return this.belongsTo(‘App/Models/Registration’)
}

When trying to await User.query().where('id', 1).with('cars.registration').first() I get: RuntimeException: E_INVALID_MODEL_RELATION: registration is not defined on Car model.

Only way that I was able to get Registration relation over user model was from pivot relation like: user.getRelated('cars').rows[0].getRelated('pivot').load('registration')

What am I doing wrong?


#2

I solved this using manyThrough relation. I was unable to find any other way of achiving this.

So this is how models are looking after implementation if anyone is interested:

User model
cars () {
return this.belongsToMany(‘App/Models/Car’)
}

Car model:
users () {
return this
.belongsToMany(‘App/Models/User’)
.pivotModel(‘App/Models/UserCar’)
}
registrations () {
return this
.manyThrough(‘App/Models/UserCar’, ‘registrations’)
}

UserCar (regular Lucid model):
registration () {
return this.belongsTo(‘App/Models/Registration’)
}