关系和逆关系不能一起工作 Adonis JS

Relation and inverse relation not working together Adonis JS

我有 3 个模型国家、州、城市 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')
  }

现在我正在尝试获取两种类型的数据 1.从国家>州>城市(正常关系) 2. 从city > state > country(反比关系)

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

现在,无论我 运行 首先将工作并给我正确的结果,但是 运行 第二种情况抛出 500 错误

this.RelatedModel.query 不是函数

现在,如果我重新启动服务器,运行 第二种情况它会工作,第一种情况将停止工作。请帮助我们面对这个问题。看起来像是查询或模型 ORM 中的某种缓存问题。

定义关系时,您需要提供命名空间而不是模型的实例。 您的状态模型将变为:

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')

  }

}

更新您的所有模型,一切都会正常工作。

没有导出模型时会出现同样的错误class,所以不要忘记导出它。

const Model = use('Model')

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