单独文件中的思考模型:如何处理 cyclical/circular 依赖项

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

我试着按照示例 here,但是没有成功。

我在 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 文件时,我在其中创建了用户和游戏的实例,我得到 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};

在我的示例中,如果您将导出默认值更改为 module.exports,一切都应该有效

您也可以尝试这个加载器,该加载器专为加载多个模型定义并使它们可用于您的应用程序而设计。

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