gpt4 book ai didi

bookshelf.js - 创建 'many-to-many' 关系

转载 作者:行者123 更新时间:2023-12-04 17:49:13 24 4
gpt4 key购买 nike

我有三个表:Schools (id, school_name)、Schools_Focuse (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);
}
});

错误:

Possibly unhandled Error: column focuses.schools_focuse_id does not exist, sql: select "focuses".*, "schools_focuses"."id" as "_pivot_id", "schools_focuses"."school_id" as "_pivot_school_id" from "focuses" inner join "schools_focuses" on "schools_focuses"."id" = "focuses"."schools_focuse_id" where "schools_focuses"."school_id" in (?)



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

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

谢谢!

最佳答案

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

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

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

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

关于bookshelf.js - 创建 'many-to-many' 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21546023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com