我很困惑如何将BelongsToMany应用于Bookshelf。
说,有一部电影属于BelongsToMany类型,例如
"The Artist" has the genres "Comedy, Drama"
我设置了一个名为join_movies_genres
的联接表,其中包含FK movie_id
和genre_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
答案 0 :(得分:4)
这有用吗?
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());
});