javascript 使用关联序列化更新

syqv5f0l  于 2023-06-20  发布在  Java
关注(0)|答案(4)|浏览(131)

在sequelize中,可以像这样一次性创建一行及其所有关联:

return Product.create({
  title: 'Chair',
  User: {
    first_name: 'Mick',
    last_name: 'Broadstone'
  }
}, {
  include: [ User ]
});

是否有等效的更新?我尽力了

model.user.update(req.body.user, {where: {id: req.user.user_id}, include: [model.profile]})

但它只是更新用户
这样做是为了创造作品

model.user.create(user, {transaction: t, include: [model.profile]})
rsaldnfx

rsaldnfx1#

首先,你必须找到模型,包括你想要更新的子模型。然后你可以得到参考的子模型,以方便地更新。我贴了一个例子供你参考。希望能有所帮助。

var updateProfile = { name: "name here" };
var filter = {
  where: {
    id: parseInt(req.body.id)
  },
  include: [
    { model: Profile }
  ]
};

Product.findOne(filter).then(function (product) {
  if (product) {
    return product.Profile.updateAttributes(updateProfile).then(function (result) {
      return result;
    });
  } else {
    throw new Error("no such product type id exist to update");
  }
});
lh80um4z

lh80um4z2#

如果要同时更新两个模型(产品和配置文件)。方法之一可以是:

// this is an example of object that can be used for update
let productToUpdate = {
    amount: 'new product amount'
    Profile: {
        name: 'new profile name'
    }
};
Product
    .findById(productId)
    .then((product) => {
        if(!product) {
            throw new Error(`Product with id ${productId} not found`);
        }

        product.Profile.set(productToUpdate.Profile, null);
        delete productToUpdate.Profile; // We have to delete this object to not reassign values
        product.set(productToUpdate);

        return sequelize
            .transaction((t) => {
                return product
                    .save({transaction: t})
                    .then((updatedProduct) => updatedProduct.Profile.save());
            })
    })
    .then(() => console.log(`Product & Profile updated!`))
nimxete2

nimxete23#

await Job.update(req.body, {
        where: {
          id: jobid
        }
      }).then(async function () {
        await Job.findByPk(jobid).then(async function (job) {
          await Position.findOrCreate({ where: { jobinput: req.body.jobinput } }).then(position => {
            job.setPositions(position.id)
          })
})

此职位属于多个职位

gzszwxb4

gzszwxb44#

这里有一个干净的方法来做到这一点:

const { Sequelize, DataTypes } = require("sequelize");
const {
  extendSequelize,
} = require("@hatchifyjs/sequelize-create-with-associations");

(async function main() {
  // create your Sequelize instance
  const sequelize = new Sequelize("sqlite::memory:", {
    logging: false,
  });

  // define your models
  const Product = sequelize.define("Product", {
    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
    title: DataTypes.STRING,
  });

  const User = sequelize.define("User", {
    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
    firstName: DataTypes.STRING,
    lastName: DataTypes.STRING,
    productId: DataTypes.INTEGER,
  });

  Product.hasOne(User, {
    as: "user",
    foreignKey: "productId",
  });

  User.belongsTo(Product, {
    as: "product",
    foreignKey: "productId",
  });

  // create the tables
  await sequelize.sync();

  // extend Sequelize
  await extendSequelize(Sequelize);

  await Product.create({
    title: "Chair",
    user: {
      firstName: "Mick",
      lastName: "Broadstone",
    },
  });

  const table = await Product.create({
    title: "Table",
  });

  await User.update(
    { lastName: "Updated", product: { id: table.id } },
    { where: { id: 1 } }
  );
})();

相关问题