addToCollection and set intermediate table column values as well

╄→尐↘猪︶ㄣ 提交于 2019-12-25 03:13:59

问题


I am using Sails v1.1 -

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.

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?

For exmaple pseudocode with 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
    }
  }
}

回答1:


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')

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.



来源:https://stackoverflow.com/questions/53850687/addtocollection-and-set-intermediate-table-column-values-as-well

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!