问题描述
我很难理解如何在objections.js中建立多对多关系的模型。
基本上,我有一个带有Users,Games和UsersScore表的应用程序。帐户可以在游戏中得分。
表是这样的:
用户表
- id
- 用户名
游戏桌
- id
- 名称
UsersScore表
- id
- userId
- gameId
- 得分
如何创建关系?
我想向登录用户显示所有游戏的列表 如果他在比赛中得分,那么他的得分
谢谢!
解决方法
这与异议文档中Join table extra properties概述的要求基本相同。您可以对其进行修改以创建users
,games
和users_games
表。然后您的User
模型可能看起来像这样:
class User extends Model {
static get relationMappings() {
return {
relation: Model.ManyToManyRelation,modelClass: Game,join: {
from: 'users.id',through: {
from: 'users_games.user_id',to: 'users_games.game_id',extra: ['score']
},to: 'game.id'
}
};
}
}
在这里您可以看到我们在score
连接表中添加了额外的users_games
列。然后,我想您会获得类似以下内容的游戏列表:
const user = await User.query().findOne({ username: 'wombatsarefluffy' });
const games = await user.$relatedQuery('games');
有关如何构造迁移的示例,请参见文档页面。