简体   繁体   English

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

[英]Relation and inverse relation not working together Adonis JS

I have 3 model Country, State, City country.js我有 3 个模型 Country、State、City country.js

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

state.js状态.js

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

city.js城市.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 )现在我正在尝试获取两种类型的数据 1.来自国家>州>城市(正常关系) 2.来自城市>州>国家(反向关系)

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现在无论我先运行哪个都可以工作并给我正确的结果但是运行第二种情况会抛出 500 错误

this.RelatedModel.query is not a function this.RelatedModel.query 不是函数

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.看起来像查询或模型 ORM 中的某种缓存问题。

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.更新所有模型,一切正常。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM