javascript - Bookshelf JS 访问模型的 idAttribute 属性的值

标签 javascript knex.js bookshelf.js

我在访问模型中的 ID 时遇到问题。我知道模型可以有一个我定义的属性 idAttribute 。我的问题是我想使用模型的 id 进行查询,但我不知道如何操作。我已阅读 bookshelfJS 文档,但无济于事。任何帮助是极大的赞赏。我的代码看起来像这样:

let Recipe = bookshelf.Model.extend({
  tableName: 'recipes',
  idAttribute: 'id',
  visible: ['name', 'description', 'prep_time', 'cook_time', 'notes', 
  'image_url', 'ingredients', 'instructions', 'tags', 'votes'],
  hasTimestamps: true,


  votes: function() {
    // return this.hasMany(RecipeVote);
    bookshelf.knex('recipes_votes')
    .sum('vote')
    .where('recipe_id', `I WANT MY MODELS ID HERE`)
    .groupBy('recipe_id')
    .then(function (result) {
      // cb(null, sum)
      console.log('SUM:', result[0].sum);
      return result[0].sum;
    })
    .catch(function (err) {
      // cb(err)
      console.log('THERE WAS AN ERROR:', err);
    });
  }
});

最佳答案

我认为你可以通过以下方式访问 id 属性:

this.attributes.id

或者

this.get('id')

关于javascript - Bookshelf JS 访问模型的 idAttribute 属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43983171/

相关文章:

javascript - 在javascript中模拟点击提交

javascript - 禁用依赖于另一个选择框的选择选项

javascript - 无需事先选择即可触发下拉选择选项的图片链接

mysql - 如何在node.js中减去knex.raw中的查询

bookshelf.js - 使用 UpdatePivot 附加 "Not Null"列

javascript - 使用 JavaScript 或 jQuery 禁用空格键或粘贴空格

mysql - Knex SQL 查询不返回任何内容,MySQL Workbench 返回正确的数据

javascript - 书架nodeJS如何选择LIMIT mysql

mysql - Knex.js 选择平均和舍入

mysql - 在 knex.js 迁移中删除外键不起作用