我正在尝试创建一个看起来像这样的数据模型:
本质上,一个用户可以属于多个项目,而一个项目可以具有多个用户。我以为我要创建一个名为UserProjects
的联接表。
但是,我不确定结构是什么样子。我在Objection中的用户模型如下:
class User extends Model {
static get tableName () {
return 'user'
}
static get relationMappings () {
return {
timesheet: {
relation: Model.HasManyRelation,
modelClass: Timesheet,
join: {
from: 'user.id',
to: 'timesheet.user_id'
}
}
}
}
}
我应该沿着
在Project
和User
上创建两个新模式
class Project extends Model {
static get tableName() {
return 'project'
}
static get relationMappings() {
return {
userprojects: {
relation: Model.HasManyRelation,
modelClass: UserProjects,
join: {
from: 'project.id',
to: 'userprojects.project_id'
}
}
}
}
}
class User extends Model {
static get tableName () {
return 'user'
}
static get relationMappings () {
return {
timesheet: {
relation: Model.HasManyRelation,
modelClass: Timesheet,
join: {
from: 'user.id',
to: 'timesheet.user_id'
}
},
userprojects: {
relation: Model.HasManyRelation,
modelClass: UserProjects,
join: {
from: 'user_id',
to: 'userprojects.user_id'
}
}
}
}
}
在这种情况下:如何将用户添加到项目中?通过UserProjects
表?
答案 0 :(得分:0)
我将创建一种方法来为模型User添加项目,例如:
class User extends Model {
static get tableName () {
return 'user'
}
static get relationMappings () {
return {
timesheet: {
relation: Model.HasManyRelation,
modelClass: Timesheet,
join: {
from: 'user.id',
to: 'timesheet.user_id'
}
},
userprojects: {
relation: Model.HasManyRelation,
modelClass: UserProjects,
join: {
from: 'user.id',
to: 'userprojects.user_id'
}
}
}
}
static getModel(knex) {
return User.bindKnex(knex)
}
static async getUser(knex, id) {
return await User.getModel(knex).query().eager('[timesheet, userprojects]').where('id', id).first()
}
async addProject(projectId){
return await this.knex()
.$relatedQuery('userprojects')
.insert({project_id: projectId})
}
}
请注意,我没有测试任何东西,只需在这里写下即可。但这就是我整理代码的方式。