我有以下型号
company.js
var Company = DB.Model.extend({
tableName: 'company',
hasTimestamps: true,
hasTimestamps: ['created_at', 'updated_at']
});
用户.js
var User = DB.Model.extend({
tableName: 'user',
hasTimestamps: true,
hasTimestamps: ['created_at', 'updated_at'],
companies: function() {
return this.belongsToMany(Company);
}
});
Company
和 User
之间存在多对多
关系,通过数据库中的下表进行处理。
user_company.js
var UserCompany = DB.Model.extend({
tableName: 'user_company',
hasTimestamps: true,
hasTimestamps: ['created_at', 'updated_at'],
users: function() {
return this.belongsToMany(User);
},
companies: function() {
return this.belongsToMany(Company);
}
});
问题是当我运行以下查询时。
var user = new User({ id: req.params.id });
user.fetch({withRelated: ['companies']}).then(function( user ) {
console.log(user);
}).catch(function( error ) {
console.log(error);
});
它记录以下错误,因为它正在查找 company_user
表而不是 user_company
。
{ [Error: select `company`.*, `company_user`.`user_id` as `_pivot_user_id`, `company_user`.`company_id` as `_pivot_company_id` from `company` inner join `company_user` on `company_user`.`company_id` = `company`.`id` where `company_user`.`user_id` in (2) - ER_NO_SUCH_TABLE: Table 'navardeboon.company_user' doesn't exist]
code: 'ER_NO_SUCH_TABLE',
errno: 1146,
sqlState: '42S02',
index: 0 }
有什么方法可以告诉它在获取关系时查找某个表吗?
最佳答案
对于 Bookshelf.js,表和 ID 在数据库中的命名方式非常重要。 Bookshelf.js 使用外键做了一些有趣的事情(即将其转换为单数并附加 _id
)。
使用Bookshelfjs的多对多功能时,不需要UserCompany
模型。但是,您需要遵循表和 ID 的命名约定才能使其正常工作。
这是多对多模型的示例。首先是数据库:
exports.up = function(knex, Promise) {
return knex.schema.createTable('books', function(table) {
table.increments('id').primary();
table.string('name');
}).createTable('authors', function(table) {
table.increments('id').primary();
table.string('name');
}).createTable('authors_books', function(table) {
table.integer('author_id').references('authors.id');
table.integer('book_id').references('books.id');
});
};
请注意联结表的命名方式:按字母顺序排列 (authors_books
)。如果您编写 books_authors
,多对多功能将无法开箱即用(您必须在模型中显式指定表名称)。另请注意外键(authors
的单数附加 _id
,即author_id)。
现在让我们看看模型。
var Book = bookshelf.Model.extend({
tableName: 'books',
authors: function() {
return this.belongsToMany(Author);
}
});
var Author = bookshelf.Model.extend({
tableName: 'authors',
books: function() {
return this.belongsToMany(Book);
}
});
既然我们的数据库已经正确命名了表和 id,我们就可以使用 ownToMany 了,这样就可以了!不需要 AuthorBook
模型,Bookshelf.js 会为您做到这一点!
这里是高级描述:http://bookshelfjs.org/#Model-instance-belongsToMany
关于node.js - model.fetch 与相关模型 bookshelfjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37113080/