如何在bookshelfjs中使用多个belongsTo?

时间:2017-12-01 09:32:29

标签: node.js angular foreign-keys angular2-forms bookshelf.js

我有一个名为“ class ”的表,它有两个外键 attendance_id syllabus_id ,但是使用JOIN我只能得到一个外键值,这是我的模型,

var AttendanceType = bookshelf.Model.extend({
   tableName: 'attendance_type',
});
var SyllabusName = bookshelf.Model.extend({
   tableName: 'syllabus_name',});
var Class = bookshelf.Model.extend({
   tableName: 'class',
AttendanceRef: function() {
   return this.belongsTo(AttendanceType);
},
SyllabusRef: function() {
   return this.belongsTo(SyllabusName);
}
});
module.exports = Class;

这是我的控制者,

.fetchAll({ withRelated: ['AttendanceRef','SyllabusRef']})

但我只从“ attendance_type ”表中获取数据。

1 个答案:

答案 0 :(得分:4)

var AttendanceType = bookshelf.Model.extend({
   tableName: 'attendance_type',
});

var syllabusName = bookshelf.Model.extend({
   tableName: 'syllabus_name',
});

var Class = bookshelf.Model.extend({
   tableName: 'class',
   AttendanceRef: function() {
      return this.belongsTo(AttendanceType,'attendance_type_id');
   },
   SyllabusNameRef: function() {
      return this.belongsTo(syllabusName,'syllabus_id');
   }
});
module.exports = Class;

这是我的控制器。

.fetchAll({ withRelated: ['AttendanceRef','SyllabusNameRef']})