【问题标题】:Relation and inverse relation not working together Adonis JS关系和逆关系不能一起工作 Adonis JS
【发布时间】:2019-05-22 11:17:03
【问题描述】:

我有 3 个模型 Country、State、City 国家.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.从城市>州>国家(反比关系)

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 中存在问题的某种缓存。

【问题讨论】:

  • 更像是一种解决方法,但您是否尝试过原始查询? await Country.query().whereRaw(city = ${state.city}, [0]).fetch();
  • @karlpy 不,但是这种方式是错误的吗?

标签: javascript relationship adonis.js


【解决方案1】:

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

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

  }

}

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

【讨论】:

    【解决方案2】:

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

    const Model = use('Model')
    
    class State extends Model {
       ...
    }
        
    module.exports = State
    

    【讨论】:

      猜你喜欢
      • 2021-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多