반응형
연결을 사용하여 업데이트 후속 처리
속편에서 행을 만드는 것은 가능하며 모든 연관성은 다음과 같습니다.
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
반응형
'programing' 카테고리의 다른 글
Chrome의 ASP.NET에서 이상한 focus_change nikkomsgchannel 오류가 발생함 (0) | 2023.09.03 |
---|---|
가져오기 오류: DLL 로드 실패: %1은 올바른 Win32 응용 프로그램이 아닙니다.하지만 DLL은 거기에 있습니다. (0) | 2023.09.03 |
조건부 춘두 생성 (0) | 2023.08.29 |
라라벨에서 BelongsToHasOne과 HasOne의 차이점은 무엇입니까? (0) | 2023.08.29 |
MariaDB가 충돌하는 이유를 찾는 방법은 무엇입니까? (0) | 2023.08.29 |