2

I have 3 model Country, State, City country.js

  state () {
    return this.hasMany(State, 'id', 'country_id')
  }

state.js

 city () {
    return this.hasMany(City, 'id', 'state_id')
  }
  stateCountry () {
    return this.belongsTo(Country, 'country_id', 'id')
  }

city.js

cityState () {
    return this.belongsTo(State, 'state_id', 'id')
  }

Now I'm trying to get two type of data 1. From country > state > city ( normal relation ) 2. From city > state > country ( inverse relation )

case 1:
const countries = await Country.query()
          .with('state.city')
          .fetch()
case 2:
const citties = await City.query()
      .with('cityState.stateCountry')
      .fetch()

Now whichever I run first will work and give me proper result however running second case throw 500 Error

this.RelatedModel.query is not a function

Now If I restart the server and run the second case it'll work and the first one will stop working. Kindly help we're facing this issue. look like some kind of caching in issue in a query or in model ORM.

TrebledJ
  • 8,713
  • 7
  • 26
  • 48
Sujal Patel
  • 2,444
  • 1
  • 19
  • 38

2 Answers2

3

When defining a relation, you need to give the namespace and not an instance of your model. Your State model will become:

const Model = use('Model')


class State extends Model {

  city () {

    return this.hasMany('App/Models/City', 'id', 'state_id')

  }

  stateCountry () {

  return this.belongsTo('App/Models/Country', 'country_id', 'id')

  }

}

Update all your model and everything should work fine.

Sujal Patel
  • 2,444
  • 1
  • 19
  • 38
0

Same error occurs when there is no export of your model class, so don't forget to export it.

const Model = use('Model')

class State extends Model {
   ...
}
    
module.exports = State