如何使用Objection.js插入2种不同类型的关系?

问题描述

TL; DR-如何插入具有多个user(ManyToMany)的product的{​​{1}}(OneToMany)?


嗨!所以我有这四个表:

categories

这些是模型:

// users
...
      table.increments('id').primary()
      table.string('name')
...

// categories
...
      table.increments('id').primary()

      table
        .integer('parent_id')
        .unsigned()
        .references('id')
        .inTable('categories')
        .onDelete('SET NULL')
        .index()

      table.string('name').notNullable()
...

// products
...
      table.increments('id').primary()

      table
        .integer('user_id')
        .unsigned()
        .references('id')
        .inTable('users')
        .onDelete('CASCADE')
        .index()

      table.text('name').notNullable()
...

// product_categories
...
      table.increments('id').primary()

      table
        .integer('product_id')
        .unsigned()
        .references('id')
        .inTable('products')
        .onDelete('CASCADE')
        .index()

      table
        .integer('category_id')
        .unsigned()
        .references('id')
        .inTable('categories')
        .onDelete('SET NULL')
        .index()
...

这是// user.ts ... static relationMappings = (): any => ({ products: { relation: Model.HasManyRelation,modelClass: Product,join: { from: 'users.id',to: 'products.user_id',},}) ... // category.ts ... static relationMappings = (): any => ({ parent: { relation: Model.BelongsToOneRelation,modelClass: Category,join: { from: 'categories.parent_id',to: 'categories.id',children: { relation: Model.HasManyRelation,join: { from: 'categories.id',to: 'categories.parent_id',products: { relation: Model.ManyToManyRelation,through: { from: 'product_categories.category_id',to: 'product_categories.product_id',to: 'products.id',}) ... // product.ts ... static relationMappings = (): any => ({ user: { relation: Model.BelongsToOneRelation,modelClass: User,join: { from: 'products.user_id',to: 'users.id',categories: { relation: Model.ManyToManyRelation,join: { from: 'products.id',through: { from: 'product_categories.product_id',to: 'product_categories.category_id',}) ... 的路由和控制者:

user

// Took reference from Objection's example koa-ts router.post('/users/:id/products',checkAuth,async (ctx: Context) => { const product = await User.relatedQuery('products') .for(ctx.params.id) .insert(ctx.request.body) return (ctx.body = product) }) 添加用户产品的示例POST请求正文:

http://localhost:8000/users/1/products

我应该用{ "name": "Product One","categories": [1,2,3] // This can be changed } 映射那些categories值吗?我相信应该有一种正确,更好的方法。

请帮助我。


堆栈:TypeScript(v3.9.7),Koa(v2.13.0),异议(v2.2.2),Knex(v0.21.2),Pg(v8.3.0),Node(v12.18.3),Postgres(v12) .3)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...