Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 续集多对多-如何创建新记录和更新联接表_Javascript_Mysql_Sequelize.js - Fatal编程技术网

Javascript 续集多对多-如何创建新记录和更新联接表

Javascript 续集多对多-如何创建新记录和更新联接表,javascript,mysql,sequelize.js,Javascript,Mysql,Sequelize.js,我正在用node、express和sequelize构建一个简单的数据库。我已经创建了模型,sequelize在数据库中创建了表 我有模型用户和城市,具有多对多关系。Sequelize创建了表Users、Cities和联接表CitiesUsers:with UserId和CityId 我的问题是,当我创建一个新用户时,如何更新该联接表?在创建时忽略CityId属性 //Models use //City.hasMany(User); //User.hasMany(City);

我正在用node、express和sequelize构建一个简单的数据库。我已经创建了模型,sequelize在数据库中创建了表

我有模型用户和城市,具有多对多关系。Sequelize创建了表Users、Cities和联接表CitiesUsers:with UserId和CityId

我的问题是,当我创建一个新用户时,如何更新该联接表?在创建时忽略CityId属性

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

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

    user.save();

在深入研究文档之后,我相信我已经找到了答案

当创建多对多关系时,sequelize将创建get、set和add方法到每个模型

从多对多用户和项目的文档中:

这将添加方法getUsers、setUsers、addUsers到Project,以及 getProjects、setProjects和addProject to User

所以在我的例子中,我做了下面的工作,其中“城市”是从城市返回的特定城市模型

//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]);
  });      
});
从文档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

创建城市模型和用户模型后,可以创建用作联接表的模型的新实例

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,
})

为了补充本文中的许多优秀答案,我发现当一个实体引用另一个实体时,如果(并且仅当)该实体不存在,我通常会创建该实体。我喜欢用这个

假设你在存储文章,每篇文章可以有任意数量的标签。您通常希望做的是:

  • 遍历所有需要的标记,并检查它们是否存在。如果它们不存在,就创建它们
  • 找到或创建所有标签后,创建文章
  • 创建文章后,将其链接到步骤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]));
      })
    })
    

    请注意,对于多对多关系,您需要对关联使用
    belongtomany
    City.belongtomany(User,{through:UserCity})
    这对我很有效,但我必须明确指定相同的事务才能绕过
    SQLITE\u错误:无法在事务中启动事务。我在这里找到了解决方案: