I’ve been trying to run this query to get the PropValue
of balance-prop
,where the userId
is equal to user.id
my relationships are as following:
Prop to PropValue – 1-M
PropValue to User – M-M through UserPropValue
Prop is not associated with User
The query in question:
const balancePropValue = await db.PropValue.findOne({
where: {
include: [
{
model: db.UserPropValue,
where: { userId: user.id },
include: {
model: db.User,
where: { id: user.id }
}
},
{
model: db.Prop,
where: { slug: "balance-slug" }
}
]
},
attributes: ['value']
});
Sequelize associations:
prop.js
associations:
static associate(models) {
models.Role.hasOne(models.Prop, { foreignKey: 'roleId', constraints: true });
}
propValue.js
associations:
static associate(models) {
models.Prop.hasMany(models.PropValue, { foreignKey: 'propId', constraints: true });
models.PropValue.belongsToMany(models.User, {
through: models.UserPropValue,
foreignKey: 'propValueId'
});
}
userPropValue.js
associations:
static associate(models) {
UserPropValue.belongsTo(models.User, { through:models.UserPropValue, foreignKey: 'userId', onDelete: 'SET NULL' });
UserPropValue.belongsTo(models.PropValue, { through:models.UserPropValue, foreignKey: 'propValueId', onDelete: 'CASCADE' });
}
user.js
associations:
static associate(models) {
models.User.belongsToMany(models.PropValue, {
through: models.UserPropValue,
foreignKey: 'userId'
});
The error I get:
Invalid value {n model: UserPropValue,n where: { userId: 1 },n include: { model: User, where: [Object] }n}
Also tried this query with where conditions:
const balancePropValue = await db.PropValue.findOne({
where: {
include: [
{
model: db.User,
where: { id: user.id },
},
{
model: db.Prop,
where: { slug: "balance-slug" },
}
]
},
attributes: ['value']
});
With this error:
Invalid value { model: User, where: { id: 1 } }
Might not be the ideal solution, but I pulled the prop entirely with its id, after that the function turned out like so:
async function systemToUserTransaction(params) {
const user = await db.User.findOne({where: {phoneNumber:params.phoneNumber}});
const prop = await db.Prop.findOne({where: {slug: "balance-prop"}});
if(!user){
throw 'User not found';
}
console.log(params.transactionType);
if(params.transactionType !== "add" && params.transactionType !== "subtract") {
throw 'No such transaction type exists';
}
balancePropValue = await db.PropValue.findOne({
include: db.User,
where:{
id: user.id
},
include: db.Prop,
where:{
propId: prop.id
}
})
console.log(balancePropValue);
value = (Number(balancePropValue.value) + Number(params.value)).toString();
balancePropValue.value = value;
console.log(balancePropValue.value);
const transaction = await new db.Transaction({
userId: user.id,
transactionType: params.transactionType,
value: params.value
})
balancePropValue.save();
transaction.save();
}