SequelizeDatabaseError: operator does not exist uuid = integer - javascript

I'm trying to make a join with two tables based on UUID (I have id too), those tables have some difficult relations...
When I run the query I get the error.
The first table is called users, and his UUID is called registry_uuid.
The second table beneficiaries but this table has two UUID, uuid_beneficiary and uuid_benefactor.
Why? because the first table has a column user_type_id and with this we can know if it's a user beneficiary or benefactor.
And the second table is to know which users are related.
Model Users:
const User = sequelize.define('users', {
registry_uuid: {
type: Sequelize.UUIDV4,
defaultValue: Sequelize.UUIDV4,
allowNull: false
},
user_type_id: {
type: Sequelize.INTEGER,
defaultValue: 1,
allowNull: false
}
}
Model Beneficiaries:
const Beneficiary = sequelize.define('beneficiaries', {
uuid_benefactor: {
type: Sequelize.UUIDV4,
defaultValue: Sequelize.UUIDV4,
allowNull: false
},
uuid_beneficiary: {
type: Sequelize.STRING,
defaultValue: Sequelize.UUIDV4,
allowNull: false
},
created_at: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW
},
disassociation_date: {
type: Sequelize.DATE,
defaultValue: null
}
}
Query:
async function getBenefactorOfBeneficiary (benefactorUuid, arrayAttributes) {
arrayAttributes = arrayAttributes || ['registry_uuid', 'name', 'last_name', 'picture']
return UserModel.findOne({
where: {
registry_uuid: {
[Op.eq]: benefactorUuid
}
},
include: [{
model: BeneficiaryModel,
}],
attributes: arrayAttributes,
raw: true
})
}
Relation:
UserModel.hasMany(beneficiaryModel, {foreignKey: 'uuid_benefactor'})
beneficiaryModel.belongsTo(UserModel, {foreignKey: 'registry_uuid'})
I expect the output:
Example:
{
"name": "string",
"lastName": "string",
"picture": "string",
"created_at" "string"
}
obviously I modify the response in controller

You should first check the models that you are including and their ID types. They must have same type. Beside that, let's say we have User and Role models. Every User can have only one role and a Role can be used by several Users. In this case, you will get this error if you write the associations wrong.
Wrong version:
// Under the user model associations
user.hasOne(models.role, { foreignKey: "roleId" });
// this will try to compare your userId with roleId of Role table
// Under the Role model associations
role.hasMany(models.user, { foreignKey: "roleId" });
Right version should be like:
// Under the user model associations
user.hasOne(models.role, { foreignKey: "roleId" });
// this will try to compare your roleId from User model with roleId of Role table
// Under the Role model associations
role.hasMany(models.user, { foreignKey: "roleId" });
If you need more details, read https://sequelize.org/master/manual/assocs.html

Related

Sequelize hasOne() / hasMany() and BelongsTo() duplicate the foregin key (creates new one and re-define it), and re-announce it as key

I've been trying to use Sequelize to manage a store front mysql db.
I followed the docs here - https://sequelize.org/master/manual/assocs.html
And did (like they said)
const Customer = sequelize.define(
"customers",
{
customer_id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
first_name: {
type: DataTypes.STRING,
allowNull: false,
},
last_name: DataTypes.STRING,
},
{ tableName: "customers" }
);
const Order = sequelize.define(
"orders",
{
order_id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
customer_id: {
type: DataTypes.INTEGER,
allowNull: false,
},
},
{ tableName: "orders" }
);
and then announce the foregin key like so:
Customer.hasMany(Order, {
foreignKey: 'customer_id'
});
Order.belongsTo(Customer);
And it creates duplicate foregin key, both the customer_id I specified and customerID as the default one.
I can overcome this by also defying foreginKey option in the belongsTo tab.
But even then I get this weird behavior that every time I run the server it "adds" another, like in the picture (from heidiSQL).
I have tried to remove the field from the define() method like #tam.teixeira suggested
And replaced the code to be:
Customer.hasMany(Order, { foreignKey: "customerID"});
Order.belongsTo(Customer);
But it still creates 2 foreginKey that way
[![enter code here][2]][2]
You need to remove the definition of
customer_id: {
type: DataTypes.INTEGER,
allowNull: false,
}
from the orders model, sequelize automatically handles that field, also since its NOT NULL you need to add that condition to the association :
Customer.hasMany(Order, {
foreignKey: {
name: 'customer_id',
allowNull: false
}
});

Sequelize asking for multiple values of association when explicitly defining foreign key

I am creating a model in sequelize as:
const Desk = sequelize.define('Desk', {
id: {
type: DataTypes.BIGINT,
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
number: {
type: DataTypes.INTEGER,
allowNull: false,
},
},
{
indexes: [
{
unique: true,
fields: ['store_id', 'number'],
message: 'A desk with same number exists on this store'
}
],
tableName: 'desk',
underscored: true,
});
I create an association as such:
Desk.belongsTo(models.Store, {
foreignKey: {
name: 'storeId',
allowNull: false
}
});
I explicitly specify the name of the foreign key so that I can add it as an index.
The problem arises when I try to create a row as such:
const data = { number: 4, storeId: 1 };
await Desk.create(data);
The above code raises an exception that StoreId cannot be null even though I explicitly changed the foreign key to storeId. Even if I try changing the data to
const data = { number: 4, StoreId: 1 };
I get the error: storeId cannot be null
I don't understand if I making some mistake in creating the model but it should not be asking me for multiple values of same field.

Problem adding allowNull in the foreignKey association 1:1 in the models with Sequelize

i am doing a simple project with node.js using Sequelize with MySQL database. I was modeling my models associations. One got the hasMany and the other the belongsTo, I set the informations in both(like, as:...,foreignKey:...,onDelete:...), and set in foreignKey the propertie allowNull. When I save de model with the belongsTo method passing the in the request body the foreignKey it saves properly. But when I do this with model that uses in association the method hasOne it doesn't work. It passes that I need to specify the model ID that uses the belongsTo method.
const connection = require('../../config/database');
const DataTypes = require('sequelize').DataTypes;
const Course = connection.define('course', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
courseName: {
type: DataTypes.STRING(50),
field: 'course_name',
allowNull: false
}
},
{ timestamps: false });
Course.associate = models => {
Course.belongsTo(models.Lecturer, {
foreignKey: {
field: 'lecturer_id',
allowNull: false
},
as: 'lecturer'
});
Course.belongsToMany(models.Student, {
through: 'student_course',
as: 'students',
foreignKey: 'curse_id',
otherKey: 'student_id'
})
}
module.exports = Course;
const connection = require('../../config/database');
const DataTypes = require('sequelize').DataTypes;
const Lecturer = connection.define('lecturer', {
lecturerName: {
type: DataTypes.STRING(50),
field: 'lecturer_name',
allowNull: false
}
},
{ timestamps: false });
Lecturer.associate = models => {
Lecturer.hasOne(models.Course, {
foreignKey: {
field: 'lecturer_id',
allowNull: false
},
as: 'course'
})
}
module.exports = Lecturer;
Result:
[ ValidationErrorItem {
message: 'course.courseId cannot be null',
type: 'notNull Violation',
path: 'courseId',
value: null,
origin: 'CORE',
instance: [Object],
validatorKey: 'is_null',
validatorName: null,
validatorArgs: [] } ]
I can't comment yet, but it looks like the error shows a camel-case column name (courseId) as opposed to a snake-case column name (course_id).
Also, you have misspelled "course_id" in your Course.belongsToMany association.

Sequelize - how to include a custom column details

I have 2 tables: User and Follower
The basic schema looks like this:
User Table
var User = sequelize.define(
"User",
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
username: DataTypes.STRING,
},
{
timestamps: true,
tableName: "users",
underscored: true
);
//Associations;
User.associate = function(models) {
User.hasMany(models.Follower, {
constraints: false,
onDelete: "cascade",
hooks: true
})
};
Follower Table
var Follower = sequelize.define(
"Follower",
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
follower_id: {
type: DataTypes.INTEGER,
foreignKey: true
},
following_id: {
type: DataTypes.INTEGER,
foreignKey: true
}
},
{
timestamps: true,
tableName: "followers",
underscored: true
}
);
//Associations;
Follower.associate = function(models) {
Follower.belongsTo(models.User, {
foreignKey: "following_id",
constraints: false
}),
Follower.belongsTo(models.User, {
foreignKey: "follower_id",
constraints: false
});
};
I want get a list of followers for a user but I want to show the user they are following and now their own data in.
I am currently running this procedure:
const following = await models.Follower.findAndCountAll({
attributes: models.Follower.fields,
where: { follower_id: user_id },
include:[
{
model: models.User,
attributes: models.User.fieldsPublic,
required: yes
}
]
})
The issue is that the include is returning the current user and not the user details of the person they are following.
Essentially the join seems to be between User.id = Follower.follower_id
How can I get it to include and join with User.id = Follower.following_id
You can add as both in your Model definition and include to be able to define which foreign key should be used (docs)
So do:
Follower.associate = function(models) {
Follower.belongsTo(models.User, {
foreignKey: "following_id",
as: 'following',
constraints: false
}),
Follower.belongsTo(models.User, {
foreignKey: "follower_id",,
as: 'follower',
constraints: false
});
};
and
...
include:[
{
model: models.User,
attributes: models.User.fieldsPublic,
as: 'follower'
required: yes
}
]
...
Alternatively, you can remove required: yes and use the where attribute to define the join condition
Furthermore, include seems to have an on attribute that is said to be similar to where (according to the docs), but I was unable to find an example.

Sequelize.js insert a model with one-to-many relationship

I have two sequelize models with one-to-many relationship. Let's call them Owner and Property.
Assume they are defined using the sails-hook-sequelize as such (simplified).
//Owner.js
module.exports = {
options: {
tableName: 'owner'
},
attributes: {
id: {
type: Sequelize.BIGINT,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING(255)
},
associations: function () {
Owner.hasMany(Property, {
foreignKey: {
name: 'owner_id'
}
});
}
}
//Property.js
module.exports = {
options: {
tableName: 'property'
},
attributes: {
id: {
type: Sequelize.BIGINT,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING(255)
}
}
Now assume I want to insert an Owner record in my database and insert a few property records to associate with the owner. How do I do this?
I'm looking for something like
Owner.create({name:'nice owner',
property: [{name:'nice property'},
{name:'ugly property'}]});
Surprisingly I can't find this in the Sequelize documentation.
You can't associate property existing records when you create the owner, you have to do that right after, with promise chain.
Owner.create({name:'nice owner'}).then(function(owner){
owner.setProperties([{name:'nice property'}, {name:'ugly property'}]).then(/*...*/);
});
To avoid any problems with those associations (owner created but some associations failed), it's better to use transactions.
sequelize.transaction(function(t) {
return Owner.create({name:'nice owner'}, {transaction: t}).then(function(owner){
return owner.setProperties([{name:'nice property'}, {name:'ugly property'}], {transaction : t});
});
});
However, if you want to create new Owner associated to new Properties you can do something like
Owner.create({
name: 'nice owner',
property: [
{ name: 'nice property'},
{ name: 'ugly property'}
]
},{
include: [ Property]
});
See http://docs.sequelizejs.com/en/latest/docs/associations/#creating-with-associations

Categories

Resources