如何在Bookshelf.js中使用自定义字段名创建多对多关系?

How do I create Many-to-Many relations with custom field names in Bookshelf.js?

本文关键字:创建 字段 关系 自定义 Bookshelf js      更新时间:2023-09-26

我想在Bookshelf.js中创建一个多对多关系,并希望自己指定fk列的名称。我还希望能够访问Bookshelf中的helper表,类似于:

var Doctor = bookshelf.Model.extend({
  patients: function() {
    return this.belongsToMany(Patient).through(Appointment);
  }
});
var Appointment = bookshelf.Model.extend({
  patient: function() {
    return this.belongsTo(Patient);
  },
  doctor: function() {
    return this.belongsTo(Doctor);
  }
});
var Patient = bookshelf.Model.extend({
  doctors: function() {
    return this.belongsToMany(Doctor).through(Appointment);
  }
});

我该怎么做?

考虑到上面的例子,我们可以这样做:

var Doctor = bookshelf.Model.extend({
  tableName: "d_doctor",
  idAttribute: "d_doctorid",
  patients: function() {
    return this.belongsToMany(Patient).through(Appointment,"a_d_doctorid","a_p_patientid");
  }
});
var Appointment = bookshelf.Model.extend({
  tableName : "a_appointment",
  idAttribute : "a_appointmentid",
  patient: function() {
    return this.belongsTo(Patient,"a_p_patientid");
  },
  doctor: function() {
    return this.belongsTo(Doctor,"a_d_doctorid");
  }
});
var Patient = bookshelf.Model.extend({
  tableName : "p_patient",
  idAttribute : "p_patientid",
  doctors: function() {
    return this.belongsToMany(Doctor).through(Appointment,"a_p_patientid", "a_d_doctorid");
  }
});