思想模型在单独的文件中:如何处理循环/循环依赖

时间:2015-09-12 05:03:00

标签: javascript thinky

我尝试按照示例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文件时,我创建了User和Game的实例,我得到了First argument of hasAndBelongsToMany must be a Model

我试着用es6语法编写它,但仍无法正常工作......

3 个答案:

答案 0 :(得分:2)

我是我的例子,如果你将export default更改为module.exports,一切都应该正常工作

答案 1 :(得分:1)

我们需要避免循环引用..

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};

答案 2 :(得分:0)

您还可以尝试使用此加载程序,其目的是加载多个模型定义并使其可供您的应用使用。

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