在单独的文件中考虑模型:如何处理循环/循环依赖关系

thinky models in separate files: how to handle cyclical/circular dependencies

本文关键字:循环 处理 何处理 依赖 关系 文件 单独 模型      更新时间:2023-09-26

我试着遵循这个例子,但是没有成功。

我有用户模型在User .js文件:

import thinky from './thinky';
let type = thinky.type;
let User = thinky.createModel('User', {
  id: type.string(),
  username: type.string(),
});
export default User;
let Game = require('./game');
User.hasAndBelongsToMany(Game, "games", "id", "id");

Game .js文件中的游戏模型:

import thinky from './thinky';
let type = thinky.type;
let Game = thinky.createModel('Game', {
  id: type.string(),
  host: type.string()
});
export default Game;
let User = require('./user');
Game.hasAndBelongsToMany(User, "players", "id", "id");

当我尝试将它们导入到test.js文件中,在那里我创建了User和Game的实例,我得到First argument of hasAndBelongsToMany must be a Model

我试着写它没有es6语法,仍然不工作…

我的例子,如果你改变导出默认为模块。导出,一切都应该正常

我们需要避免循环引用,所以…

user.js

import thinky from './thinky';
let type = thinky.type;
let User = thinky.createModel('User', {
  id: type.string(),
  username: type.string(),
});
export default User;

game.js

import thinky from './thinky';
let type = thinky.type;
let Game = thinky.createModel('Game', {
  id: type.string(),
  host: type.string()
});
export default Game;

index.js

import User from './user';
import Game from './game';
Game.hasAndBelongsToMany(User, "players", "id", "id");
User.hasAndBelongsToMany(Game, "games", "id", "id");
export {User, Game};

你也可以尝试这个加载器,它是为加载多个模型定义而设计的,并使它们在你的应用程序中可用。

https://github.com/mwielbut/thinky-loader