BookshelfJS:如何申请BelongsToMany?

pos*_*eid 1 bookshelf.js

我很困惑如何将 BelongsToMany 与 Bookshelf 一起应用。

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

"The Artist" has the genres "Comedy, Drama"
Run Code Online (Sandbox Code Playgroud)

我设置了一个名为join_movies_genresFKmovie_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 } }
Run Code Online (Sandbox Code Playgroud)

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

模型的当前状态是:

var 电影 = bookshelf.Model.extend({
    表名: '电影',

    流派:函数(){
      // 返回 this.belongsToMany(Genre, 'join_movies_genres', 'movie_id', 'genre_id', {debug: true});
      // 返回 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 类型 = bookshelf.Model.extend({
    表名:'流派'
});

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

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

ugl*_*ode 5

这有效吗?

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());
});
Run Code Online (Sandbox Code Playgroud)