本文介绍了addToCollection 并设置中间表列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Sails v1.1 -

I am using Sails v1.1 -

遵循风帆上通过"关联的示例 - https://sailsjs.com/documentation/concepts/models-and-orm/associations/through-associations

Following the example from the "Through" associations on sails - https://sailsjs.com/documentation/concepts/models-and-orm/associations/through-associations

他们将直通"关联定义为基本上是自定义模型.所以这真的不是通过",它只是控制多对多关系的连接表.

They defined a "through" association as basically a custom model. So this really isn't "through", it's just controlling the join table for the many to many relation.

所以在中间模型中,我添加了一个isTyping的自定义属性,如下所示.

So in the intermediate model, I added a custom attribute of isTyping seen below.

是否可以同时添加到集合并设置这个中间值?

Is it possible to add to collection and set this intermediate value at same time?

例如带有setIntermediate的伪代码:

User.addToCollection(userId, 'pets', petId).setIntermediate('isTyping', true);

所以按照文档上的例子:

So following the example on the docs:

myApp/api/models/User.js

module.exports = {

  attributes: {
    name: {
      type: 'string'
    },
    pets:{
      collection: 'pet',
      via: 'owner',
      through: 'petuser'
    }
  }
}

myApp/api/models/Pet.js

module.exports = {
  attributes: {
    name: {
      type: 'string'
    },
    color: {
      type: 'string'
    },
    owners:{
      collection: 'user',
      via: 'pet',
      through: 'petuser'
    }
  }
}

myApp/api/models/PetUser.js

module.exports = {
  attributes: {
    owner: {
      model:'user'
    },
    pet: {
      model: 'pet'
    },
    // I ADDED THIS INTERMEDIATE COLUMN NAME in the join table
    isTyping: {
      type: 'boolean',
      defaultsTo: false
    }
  }
}

推荐答案

我不知道这是否正确,但这样做的方法是使用 Pet.addToCollection(petId, 'owners',userId)/User.addToCollection(userId, 'pets', petId)Pet.removeFromCollection(petId, 'owners', userId)/User.removeFromCollection(userId, 'pets', petId),改为:

I don't know if this is right, but the way to do this is instead of using Pet.addToCollection(petId, 'owners', userId)/User.addToCollection(userId, 'pets', petId) or Pet.removeFromCollection(petId, 'owners', userId)/User.removeFromCollection(userId, 'pets', petId), is to instead do:

PetUser.create({ owner: userId, pet: petId, isTyping: true }).populate('user').populate('pet')

我不确定是否正确,这不支持 addToCollection/removeFromCollection 支持的数组参数.并且您还必须对数据进行处理,以获取具有 isTyping 的枢轴属性的 owners/pets 列表.

I'm not sure if right, and this doesn't support the array argument that addToCollection/removeFromCollection does. And you also have to massage the data in order to get a list of owners/pets with the pivot attribute of isTyping.

这篇关于addToCollection 并设置中间表列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 12:19