BookshelfJS:如何申请BelongsToMany?

BookshelfJS: How to apply BelongsToMany?

我很困惑如何将 BelongsToMany 应用到 Bookshelf。

说,有一部属于许多类型的电影,例如

"The Artist" has the genres "Comedy, Drama"

我已经设置了一个名为 join_movies_genres 的联接 table,它具有 FK movie_idgenre_id

我尝试从具有和不具有 through(...) 定义的电影中获取流派。但是我得到了未定义的目标,类似于:

relatedData:
 { type: 'belongsToMany',
   target:
   { [Function]
    NotFoundError: [Function: ErrorCtor],
    NoRowsUpdatedError: [Function: ErrorCtor],
    NoRowsDeletedError: [Function: ErrorCtor] },
 targetTableName: 'genres',
 targetIdAttribute: 'id',
 joinTableName: 'join_movies_genres',
 foreignKey: { debug: true },
 otherKey: undefined,
 parentId: 1,
 parentTableName: 'movies',
 parentIdAttribute: 'id',
 parentFk: 1,
 throughTarget:
  { [Function]
    NotFoundError: [Function: ErrorCtor],
    NoRowsUpdatedError: [Function: ErrorCtor],
    NoRowsDeletedError: [Function: ErrorCtor] },
 throughTableName: 'join_movies_genres',
 throughIdAttribute: 'id',
 throughForeignKey: { debug: true } }

那么,我将如何建立这种关系?如何启用调试输出?

模型的当前状态是:

var Movie = bookshelf.Model.extend({
    tableName: 'movies',

    genres: function() {
      // return this.belongsToMany(Genre, 'join_movies_genres', 'movie_id', 'genre_id', {debug: true});
      // return this.belongsToMany(Genre).through(JoinMovieGenre, 'movie_id', 'genre_id');
      return this.belongsToMany(Genre, 'join_movies_genres', 'movie_id', 'genre_id').through(JoinMovieGenre, {debug: true});
    }
});

var Genre = bookshelf.Model.extend({
    tableName: 'genres'
});

new Movie({title: 'The Artist'}).fetch({debug: true}).then(function(m) {
  console.log(m.toJSON());
  console.log(m.genres())
})

此代码的沙箱位于 https://github.com/mulderp/bookshelf-demo/tree/cli_migrations

这个有用吗?

var Movie = bookshelf.Model.extend({
    tableName: 'movies',

    genres: function() {
      return this.belongsToMany(Genre, 'join_movies_genres', 'movie_id', 'genre_id');
    }
});

var Genre = bookshelf.Model.extend({
    tableName: 'genres'
});

new Movie({title: 'The Artist'}).fetch({withRelated:['genres']}).then(function(m) {
  console.log(m.toJSON());
});