我有两种模式:
const Post = Bookshelf.Model.extend({
tableName: 'post',
tags: function () {
return this.belongsToMany(Tag)
}
});
const Tag = Bookshelf.Model.extend({
tableName: 'tag'
});
我想获取Post
的集合的标签。
我试过了:
const Tags = new Bookshelf.Collection([
Post.forge({
id: 1
}),
Post.forge({
id: 2
})
])
.fetch({
withRelated: [
'tags'
]
})
.then((collection) => {
console.log('collection', collection.toJSON());
});
这会出错:
未处理拒绝错误:ER_BAD_TABLE_ERROR:未知表格'未定义'
我假设此错误是因为Bookshelf.Collection
无法识别第一个参数是模型列表。但是,documentation表示它是预期的输入:
new Collection([models], [options])
答案 0 :(得分:0)
这有效:
PostModel
.query('where', 'id', 'in', [1])
.fetchAll({
withRelated: [
'badges'
]
})
.call('toJSON');
它会产生一个查询:
select
`badge`.*,
`badge_post`.`post_id` as `_pivot_post_id`,
`badge_post`.`badge_id` as `_pivot_badge_id`
from
`badge`
inner join
`badge_post` on `badge_post`.`badge_id` = `badge`.`id`
where
`badge_post`.`post_id` in (?, ?, ?)