BookshelfJS - 'withRelated' 通过关系 table returns 空结果

BookshelfJS - 'withRelated' through relational table returns empty results

我一直在尝试在我的数据库中构建关系以便更有效地查询和连接,但是在遵循 '.belongsToMany'' 的指南之后.through''.belongsTo' 我现在得到的结果是空的。

我有一个 Sound 模型和一个 Keyword 模型,我想用多对多关系建模(每个声音可以有多个关键字,每个关键字可以与多个声音相关)。根据文档,“.belongsToMany”将是此处使用的关系。

我使用 'sound_keyword' 关系 table/SoundKeyword 关系模型(其中每个条目都有自己独特的'id',一个'soundID',一个'keywordID' ):

var Sound = bookshelf.Model.extend({
  tableName: 'sounds',
  keywords: function () {
    return this.belongsToMany(Keyword, 'sound_keyword', 'id', 'id').through(SoundKeyword, 'id', 'soundID');
  },
});

var Keyword = bookshelf.Model.extend({
  tableName: 'keywords',
  sounds: function () {
    return this.belongsToMany(Sound, 'sound_keyword', 'id', 'id').through(SoundKeyword, 'id', 'keywordID');
  }
});

其中:

var SoundKeyword = bookshelf.Model.extend({
    tableName: 'sound_keyword',
    sound: function () {
        return this.belongsTo(Sound, 'soundID');
    },
    keyword: function () {
        return this.belongsTo(Keyword, 'keywordID');
    }
});

根据我在文档和 BookshelfJS GitHub 页面中阅读的内容,上述内容似乎是正确的。尽管如此,当我 运行 以下查询 我得到一个空的结果集(有问题的声音与 3 个关键字相关在数据库中):

var results = await Sound
    .where('id', soundID)
    .fetch({
        withRelated: ['keywords']
    })
    .then((result) => {
        console.log(JSON.stringify(result.related('keywords')));
    })

我哪里出错了?关系是否设置不正确(可能是错误的外键?)?我是否错误地获取了相关模型?

很高兴根据需要提供 Knex 设置。

更新编辑:

我从一开始就一直在使用 Model-Registry Plugin,后来忘记了。事实证明,虽然下面的语法是正确的,但它更喜欢类似于以下的语法(即小写 'model',删除 '.extends' 并将模型名称放在引号中):

var Sound = bookshelf.model('Sound',{
  tableName: 'sounds',
  keywords: function () {
    return this.belongsToMany('Keyword', 'sound_keyword', 'soundID', 'keywordID');
  },
});

var Keyword = bookshelf.model('Keyword',{
  tableName: 'keywords',
  sounds: function () {
    return this.belongsToMany('Sound', 'sound_keyword', 'keywordID', 'soundID');
  }
});

希望对其他人有所帮助。

似乎删除“.through”关系并更改“.belongsToMany”调用中的 ID 就成功了(如下所示),但我不完全确定原因(文档似乎暗示 belongsToMany 和 .through 可以很好地协同工作——可能是多余的?)

var Sound = bookshelf.Model.extend({
  tableName: 'sounds',
keywords: function () {
    return this.belongsToMany(Keyword, 'sound_keyword', 'soundID', 'keywordID');
  },
});

var Keyword = bookshelf.Model.extend({
  tableName: 'keywords',
  sounds: function () {
    return this.belongsToMany(Sound, 'sound_keyword', 'keywordID', 'soundID');
  }
});

我确实尝试过使用 soundIDkeywordId 而不是 'id' 的原始代码(如下所示),但没有 .through 关系并且给出了相同的空结果。