我需要一些关于风帆0.12.13与postgresql的关联的帮助。 我有一个" App"模特和"会员资格"模型。关系应该是一对多(一个app可以与许多关系相关联)。 这是App模型db表模式(表称为" apps"):
Table "public.apps"
Column | Type | Modifiers
------------+-----------------------------+---------------------------------------------------
id | integer | not null default nextval('apps_id_seq'::regclass)
name | character varying | not null
Indexes:
"apps_pkey" PRIMARY KEY, btree (id)
"apps_name_key" UNIQUE CONSTRAINT, btree (name)
Referenced by:
TABLE "memberships" CONSTRAINT "app_fk" FOREIGN KEY (app_id) REFERENCES apps(id) ON UPDATE RESTRICT ON DELETE CASCADE
这是会员资格:
Table "public.memberships"
Column | Type | Modifiers
------------+-----------------------------+----------------------------------------------------------
id | integer | not null default nextval('memberships_id_seq'::regclass)
app_id | integer | not null
Foreign-key constraints:
"app_fk" FOREIGN KEY (app_id) REFERENCES apps(id) ON UPDATE RESTRICT ON DELETE CASCADE
在我的用户模型中,我有这个:
module.exports = {
tableName: 'apps',
autoCreatedAt: false,
autoUpdatedAt: false,
attributes: {
name: { type: 'string', unique: true, required: true, alphanumericdashed: true },
memberships: { collection: 'memberships', model: 'Membership' },
}
}
这是会员制模式:
module.exports = {
tableName: 'memberships',
autoCreatedAt: false,
autoUpdatedAt: false,
attributes: {
app: { model: 'app', columnName: 'app_id' },
},
};
当我尝试查询应用并获得其成员资格时:
App.find({ id: 1 }).populate('memberships').exec((err, app) => {
if (err) throw err;
console.log(app.memberships);
});
我收到此错误:
Error (E_UNKNOWN) :: Encountered an unexpected error
error: column apps.memberships does not exist
at Connection.parseE (/usr/src/app/node_modules/sails-postgresql/node_modules/pg/lib/connection.js:539:11)
at Connection.parseMessage (/usr/src/app/node_modules/sails-postgresql/node_modules/pg/lib/connection.js:366:17)
at Socket.<anonymous> (/usr/src/app/node_modules/sails-postgresql/node_modules/pg/lib/connection.js:105:22)
at emitOne (events.js:115:13)
at Socket.emit (events.js:210:7)
at addChunk (_stream_readable.js:252:12)
at readableAddChunk (_stream_readable.js:239:11)
at Socket.Readable.push (_stream_readable.js:197:10)
at TCP.onread (net.js:589:20)
看起来关联不是&#34;已启用&#34;和水线正在寻找一个真正的专栏&#34;会员资格&#34;在我的模型中。谁能解释一下我做错了什么? THX
答案 0 :(得分:2)
根据documentation,我猜你的关联不好。
// App.js
module.exports = {
tableName: 'apps',
autoCreatedAt: false,
autoUpdatedAt: false,
attributes: {
name: {
type: 'string',
unique: true,
required: true,
alphanumericdashed: true
},
memberships: {
collection: 'membership', // <-- changed to singular (as your model should be)
via: 'app' // <-- use "via" instead of "model"
},
}
}
// Membership.js
module.exports = {
tableName: 'memberships',
autoCreatedAt: false,
autoUpdatedAt: false,
attributes: {
app: {
model: 'app'
// <-- removed the "columnName" here
},
},
};
此外,约定通常会将您的模型命名为单数实例。例如,它的“User.js”而不是“Users.js”。将集合称为复数是有效的。我对您的命名进行了一些更改,但您必须看看它是如何影响您的文件的(因为您没有提供这些名称)。