建立“多对多”关系

时间:2014-02-04 07:05:08

标签: bookshelf.js

我有三个表:Schools(id,school_name),Schools_Focuses(id,school_id,focus_id)和Focuses(id,focus),并希望在我的Schools模型上创建一个返回所有相关焦点的方法。

我可以执行我想要对此SQL QUERY执行的操作:

SELECT focus FROM focuses INNER JOIN schools_focuses ON focuses.id = schools_focuses.focus_id INNER JOIN schools ON schools.id = schools_focuses.school_id WHERE schools.id = 36;

型号代码:

// Define Models
exports.School = School = Bookshelf.PG.Model.extend({
  tableName: 'schools',

  focuses: function() {
    return this.hasMany(Focus).through(Schools_Focuses);
  }
});

错误:

  

可能未处理错误:列focus.schools_focuse_id不存在,sql:选择“focused”。*,“schools_focuses”。“id”为“_pivot_id”,“schools_focuses”。“school_id”为“_pivot_school_id”来自“focus” “inner join”schools_focuses“on”schools_focuses“。”id“=”focus“。”schools_focuse_id“where”schools_focuses“。”school_id“in(?)

我不希望在Focuses中有这个额外的列(focused.schools_focuse_id),因为焦点可以归属于多个学校。

如何正确设置?我玩过外键和其他键用于hasMany()和through(),但没有运气。

谢谢!

2 个答案:

答案 0 :(得分:8)

听起来你需要使用belongsToMany()而不是hasMany()。

// Define Models
exports.School = School = Bookshelf.PG.Model.extend({
  tableName: 'schools',

  focuses: function() {
    return this.belongsToMany(Focus, 'schools_focuses');
  }
});

第二个参数是必需的,因为连接表不是alpha顺序('focused_schools')。如果在识别连接键(school_id,focus_id)时遇到问题,您也可以将这些键作为参数覆盖。此外,由于它在内部使用连接表,因此您无需为Schools_Focuses创建单独的模型。

答案 1 :(得分:0)

如果我们不需要为Schools_Focuses创建单独的模型,那么我们如何从联结表中查询数据,即:

'SELECT * FROM focuses_schools WHERE focus_id = 2 & school_id = 1'