programing

연결을 사용하여 업데이트 후속 처리

linuxpc 2023. 8. 29. 20:13
반응형

연결을 사용하여 업데이트 후속 처리

속편에서 행을 만드는 것은 가능하며 모든 연관성은 다음과 같습니다.

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

먼저 업데이트할 하위 모델을 포함한 모델을 찾아야 합니다.그러면 당신은 쉽게 업데이트할 하위 모델의 참조를 얻을 수 있습니다. 저는 당신의 참조를 위해 예제를 게시합니다.도움이 되기를 바랍니다.

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");
  }
});

두 모델(제품 및 프로파일)을 한 번에 업데이트하려는 경우.접근 방식 중 하나는 다음과 같습니다.

// 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!`))
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)
          })
})

이 직위는 많은 작업에 속합니다.

이를 위한 깨끗한 방법은 다음과 같습니다.

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 } }
  );
})();

언급URL : https://stackoverflow.com/questions/33918383/sequelize-update-with-association

반응형