model.fetch 与相关模型 bookshelfjs

model.fetch with related models bookshelfjs

我有以下型号

company.js

var Company = DB.Model.extend({
  tableName: 'company',
  hasTimestamps: true,
  hasTimestamps: ['created_at', 'updated_at']
});

user.js

var User = DB.Model.extend({
  tableName: 'user',
  hasTimestamps: true,
  hasTimestamps: ['created_at', 'updated_at'],
  companies: function() {
    return this.belongsToMany(Company);
  }
});

CompanyUser 之间存在 many-to-many 关系,通过数据库中的以下 table 处理。

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 table 而不是 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 }

有什么办法让它在获取关系时寻找某个table?

对于 Bookshelf.js 非常重要,table 和 ID 在数据库中的命名方式。 Bookshelf.js 使用外键做了一些有趣的事情(即将其转换为单数并附加 _id)。

使用 Bookshelfjs 的多对多功能时,不需要 UserCompany 模型。但是,您需要遵循 tables 和 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');
  });
};

请注意路口 table 的命名方式:按字母顺序排列 (authors_books)。如果您编写 books_authors,那么多对多功能将无法开箱即用(您必须在模型中明确指定 table 名称)。还要注意外键(单数 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);
  }
});

现在我们的数据库已经正确命名了 tables 和 id,我们可以只使用 belongsToMany 并且这有效!不需要 AuthorBook 模型,Bookshelf.js 会为您完成!

这是高级说明:http://bookshelfjs.org/#Model-instance-belongsToMany

其实我找到了一个非常简单的解决方案。您只需要像这样提及 table 名称:

var User = DB.Model.extend({
  tableName: 'user',
  hasTimestamps: true,
  hasTimestamps: ['created_at', 'updated_at'],
  companies: function() {
   return this.belongsToMany(Company, **'user_company'**);
  }
})

正如@uglycode 所说,不再需要 UserCompany 模型。