javascript 多对多序列化-如何创建新记录和更新连接表

b1zrtrql  于 2023-03-16  发布在  Java
关注(0)|答案(4)|浏览(118)

我正在用node,express和sequelize构建一个简单的数据库,我已经创建了我的模型,sequelize在我的数据库中创建了表。
我有模型用户和城市,具有多对多的关系。Sequelize创建了表用户,城市和连接表CitiesUsers:具有用户ID和城市ID。
我的问题是,当我创建一个新用户时,如何更新连接表?CityId属性在创建时被忽略。

//Models use 
   //City.hasMany(User);
   //User.hasMany(City);

   var user = User.build({
      first_name: 'John',
      last_name: 'Doe',
      CityId: 5
    });

    user.save();
r7xajy2e

r7xajy2e1#

在深入研究文档之后,我相信我已经找到了答案。
当创建多对多关系时,sequelize为每个模型创建get、set和add方法。
根据文档,假设用户和项目模型为多对多:http://docs.sequelizejs.com/en/latest/docs/associations/#belongs-to-many-associations
这将添加方法getUsers、setUsers、addUsers到项目,以及getProjects、setProjects和addProject到用户。
因此,在我的例子中,我执行了以下操作,其中“city”是从City.find返回的特定City模型...

//user.setCities([city]);

models.User.find({ where: {first_name: 'john'} }).on('success', function(user) {
  models.City.find({where: {id: 10}}).on('success', function(city){
    user.setCities([city]);
  });      
});
q3qa4bjr

q3qa4bjr2#

创建City和User模型后,您可以创建模型的新示例,用作连接表。

const User = sequelize.define('user')
const City = sequelize.define('city')
const UserCity = sequelize.define('user_city')

User.belongsToMany(City, { through: UserCity })
City.belongsToMany(User, { through: UserCity })

const user = await User.create()
const city = await City.create()

const userCity = await UserCity.create({
  userId: user.userId,
  cityId: city.cityId,
})
kgqe7b3p

kgqe7b3p3#

我发现,当我有一个实体引用另一个实体时,当(且仅当)它不存在时,我想创建被引用的实体,为此,我喜欢使用findOrCreate()
假设你在存储文章,每篇文章可以有任意数量的标签,你通常会想做的是:
1.遍历所有需要的标签,检查它们是否存在。如果不存在,创建它们。
1.一旦找到或创建了所有的标签,创建您的文章。
1.创建文章后,将其链接到您在步骤1中查找(或创建)的标记。
对我来说,这看起来像是:

const { article, tags } = model.import("./model/article");

let tagging = [
  tags.findOrCreate({where: {title: "big"}}),
  tags.findOrCreate({where: {title: "small"}}),
  tags.findOrCreate({where: {title: "medium"}}),
  tags.findOrCreate({where: {title: "xsmall"}})
];

Promise.all(tagging).then((articleTags)=> {
  article.create({
    title: "Foo",
    body: "Bar"    
  }).then((articleInstance) => {
    articleInstance.setTags(articleTags.map((articleTag) => articleTag[0]));
  })
})
jslywgbw

jslywgbw4#

来自文档v3:

// Either by adding a property with the name of the join table model to the object, before creating the association
project.UserProjects = {
  status: 'active'
}
u.addProject(project)

// Or by providing a second argument when adding the association, containing the data that should go in the join table
u.addProject(project, { status: 'active' })

// When associating multiple objects, you can combine the two options above. In this case the second argument
// will be treated as a defaults object, that will be used if no data is provided
project1.UserProjects = {
    status: 'inactive'
}

u.setProjects([project1, project2], { status: 'active' })
// The code above will record inactive for project one, and active for project two in the join table

相关问题