简体   繁体   English

Bookshelf JS:“this.hasOne”不是一个函数

[英]Bookshelf JS: “this.hasOne” is not a function

Attempting to work through the simplest examples of bookshelf, but can't get past a one-to-many relationship using "withRelated" in a fetch statement. 试图通过最简单的书架示例,但在fetch语句中使用“withRelated”无法超越一对多的关系。 Here is my code (with some things removed for privacy) representing a one-to-many from B to A. 这是我的代码(隐藏了一些东西)代表从B到A的一对多。

"use strict";
var knex = require('knex') ({
    client: 'mysql',
    connection: {
        host: '127.0.0.1',
        user: '*******',
        password: '*******',
        database: '*******',
        charset: 'utf8'
    }
});

var bookshelf = require('bookshelf')(knex);

var A, B

A = bookshelf.Model.extend({
    tableName: 'A',
    propB: () => { 
         return this.hasOne(B, 'A_id') 
    }

B = bookshelf.Model.extend({
    tableName: 'B',
    propA: () => { return this.belongsTo(A, 'A_id') }
})

A.forge().fetch({withRelated: ['propB']}).then(function(x){console.log(x)})

However, running this I get "Unhandled rejection TypeError: this.hasOne is not a function", referring to the this.hasOne in A. If I remove the "withRelated" clause, it runs just as expected and returns the correct entry in the database. 然而,运行这个我得到“Unhandled rejection TypeError:this.hasOne不是一个函数”,引用A中的this.hasOne。如果我删除“withRelated”子句,它会按预期运行并返回正确的条目数据库。

Why am I receiving this error? 为什么我收到此错误? More info: Nodejs: v4.4.1 Bookshelf: v0.9.4 更多信息:Nodejs:v4.4.1 Bookshelf:v0.9.4

You are using arrow functions which inherit this from its parent context. 您正在使用从其父上下文继承this功能的箭头函数。 You need to use function() {} syntax, so that bookshelf can bind this correctly. 您需要使用function() {}语法,以便bookshelf可以正确绑定this

Shorthand function notation is shorter and binds to the this-context of the class. 速记函数表示法较短,并且与该类的上下文绑定。

var A = bookshelf.Model.extend({
    tableName: 'A',
    propB() { 
        return this.hasOne(B, 'A_id') 
    }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM