【发布时间】:2018-07-07 16:05:17
【问题描述】:
我想弄清楚的是如何获取当前经过身份验证的用户的 id 并在数据库中创建记录时将其用作不同模型的外键?
更具体地说,我需要获取当前经过身份验证的用户(模型:CommonUser)的 id,并在创建新事件时使用该 id 作为 FK。
关系:
我创建了一个基于名为 CommonUser 的用户模型的模型。普通用户有很多事件。事件属于普通用户。
所以 Event 有一个名为 commonUserId 的外键。
如何获取用户的 id 并在插入时使用它?
就建立关系而言,我会认为这将作为过程的一部分自动进行?这是不正确的吗?
为了使事情复杂化,我有一个事件查找表(我接下来会担心这个,所以不要觉得有必要深入研究),因为事件也通过事件查找具有AndBelongsToMany。
用户
{
"name": "CommonUser",
"base": "User",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {},
"validations": [],
"relations": {
"events": {
"type": "hasMany",
"model": "Event",
"foreignKey": "eventId",
"through": "EventLookUp"
},
"friends": {
"type": "hasMany",
"model": "CommonUser",
"through": "Friend",
"foreignKey": "friendId"
}
},
"acls": [],
"methods": {}
}
事件
{
"name": "Event",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"name": {
"type": "string"
},
"radius": {
"type": "number",
"default": 50
},
"status": {
"type": "number"
},
"location": {
"type": "geopoint",
"required": true
}
},
"validations": [],
"relations": {
"owner": {
"type": "belongsTo",
"model": "CommonUser",
"foreignKey": "commonUserId"
},
"commonUsers": {
"type": "hasAndBelongsToMany",
"model": "CommonUser",
"foreignKey": "ownerId",
"through": "EventLookUp"
},
"galleries": {
"type": "hasOne",
"model": "Gallery",
"foreignKey": ""
},
"photos": {
"type": "hasMany",
"model": "Photo",
"foreignKey": "",
"through": "Gallery"
}
},
"acls": [],
"methods": {}
}
事件查找
{
"name": "EventLookUp",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
如果我能指出正确的方向,那就太好了。阅读文档很难找到答案。 我认为我需要在插入和设置事件模型属性之前使用操作挂钩? 就这方面而言,环回的最佳实践是什么?
【问题讨论】:
标签: node.js rest express loopbackjs