Sequelize : How to do left outer join? - node.js

My issue is related to the query,
I want to get all the products with it's related category.
And a product can have multiple Category
My Product table is
IdProduct: {
primaryKey: true,
type: Sequelize.INTEGER,
allowNull: false,
autoIncrement: true,
},
CommodityClass: {
type: Sequelize.INTEGER,
allowNull: false,
}
My Category Table is
IdProductCategory: {
primaryKey: true,
type: Sequelize.INTEGER,
allowNull: false,
autoIncrement: true
},
Name: {
type: Sequelize.STRING,
allowNull: false
}
and my productcategoryproduct table is (It contains the id of product and category)
IdProductCategory: {
type: Sequelize.INTEGER,
primaryKey: true,
allowNull: false,
references: {
model: 'ProductCategory',
key: 'IdProductCategory',
}
},
IdProduct: {
type: Sequelize.INTEGER,
primaryKey: true,
allowNull: false,
references: {
model: 'Product',
key: 'IdProduct',
}
}
I have used association as
Product.hasMany(ProductCategoryProduct);
// Product Association
ProductCategoryProduct.belongsTo(Product, { foreignKey: 'IdProduct'});
My query is
Product.findAll({
include: {
all: true
}
})
.then((results) => {
...
})
But I'm getting the error
"message":"Invalid column name 'productIdProduct'
Can someone please help me in this?

Related

Sequelize hasOne join: Include unexpected. Element has to be either a Model, an Association or an object

I want to establish a relationship between two tables using a foreign key to read me the description (funzione string(40)). My models and code:
first model:
id: {
autoIncrement: true,
type: Sequelize.INTEGER,
allowNull: false,
primaryKey: true
},
id_user: {
type: Sequelize.INTEGER,
allowNull: false
},
id_role: {
type: Sequelize.INTEGER,
allowNull: false
},
id_funzione: {
type: Sequelize.INTEGER,
allowNull: false
}
}, {
sequelize,
tableName: 'abilitazioni',
schema: 'public',
timestamps: false,
indexes: [
{
name: "pk_abilitazioni",
unique: true,
fields: [
{ name: "id"},
]
},
]
Second model:
id: {
autoIncrement: true,
type: Sequelize.INTEGER,
allowNull: false,
primaryKey: true
},
funzione: {
type: Sequelize.STRING(40),
allowNull: false
}
}, {
sequelize,
tableName: 'funzioni',
schema: 'public',
timestamps: false,
indexes: [
{
name: "pk_funzioni",
unique: true,
fields: [
{ name: "id_funzione" },
]
},
]
The relation
db.Abilitazioni.hasOne(db.Funzioni, {
foreignKey: 'id_funzione'
});
db.Funzioni.belongsTo(db.Abilitazioni);
find on db
Abilitazioni.findAll({
where: { id_role: id
},
include: [{
Funzioni,
}]
})
I tried to create a one to one relationship to read a description
field with the foreign key.
This query :
SELECT funzioni.id , funzioni.funzione , funzioni.access_level
from public.abilitazioni, public.funzioni
where abilitazioni.id_user = 1 and id_role= 1 and
abilitazioni.id_funzione = funzioni.id ;

How to findAll query where value is from associated table in Sequelize?

I am using Sequelize as my ORM and I want to know the best way to achieve the desired outcome.
With the models below, how do I return an array that returns all the Books and Novels while removing duplicates that have the same author+title.
var Book = sequelize.define('Book', {
id: {
type: DataTypes.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true
},
title: {
type: DataTypes.STRING
},
author: {
type: DataTypes.STRING
}
//....other columns
})
var Novel = sequelize.define('Novel', {
id: {
type: DataTypes.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true
},
title: {
type: DataTypes.STRING
},
author: {
type: DataTypes.STRING
}
//...other different columns
})

Sequelize Multi Inserting Data

Hi everybody =) It's my first time using sequelize with postgresql, and I have problem with multi inserting data with sequelize(node.js). We have some tables(see in pic)
Table Relations
1) Clients -> 1:M -> Contracts
2) Contracts -> 1:M -> Contracts_attaches
3) Rates -> 1:M -> Contracts_attaches
Clients Model
const Client = db.define('clients', {
id_clients: {
type: Sequelize.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true,
},
nclients: {
type: Sequelize.STRING
}
-some fields-
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
Rate Model
const Rate = db.define('rates', {
id_rates: {
type: Sequelize.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true
}
--fields--
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
})
Contract Model
const Contract = db.define('contracts', {
id_contracts: {
type: Sequelize.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true
},
--fields--
id_clients: {
type: Sequelize.INTEGER,
allowNull: false
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
})
Contract_attach Model
const Contract_attach = db.define('contract_attach', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true
},
contracts_id: {
type: Sequelize.INTEGER,
references:{
model:'contracts',
key:'id_contracts'
}
},
rate_id: {
type: Sequelize.INTEGER
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
},
})
Association config
Contract.belongsTo(Contract_attach, { foreignKey:'id_contracts', sourceKey:'contracts_id' });
Contract_attach.hasMany(Contract,{foreignKey:'id_contracts', sourceKey:'contracts_id'});
Contract_attach.hasMany(Rate,{foreignKey: 'id_rates', sourceKey: 'rate_id'});
Rate.belongsTo(Contract_attach, { foreignKey: 'rate_id', sourceKey: 'id_rates' });
Example Inserting Data
I try insert data like this code
Contract.create({'numcontract':22,'datereg':'2019-12-11','id_clients':5,Contract_attach:[{'rate_id':2,'rate_id':3}]},
{include: [Contract_attach]}).then(result => console.log(result));
or this code
Contract.create({'numcontract':22,'datereg':'2019-12-11','id_clients':5,Contract_attach:[{'ratename':'Small Buissness','ratename':'Small Buissness 10'}]},
{include: [Contract_attach]}).then(result => console.log(result));
When I try insert data with this code, sequelize inserting data just for Contract table, and ignoring insert to Contract_attach.
PS. Rate table have data, and we don't need insert data to the Rate table.
For some, it may and will be useful, but I solved this problem like this
Contr.create({'numcontract':22,'datereg':'2019-12-11','id_clients':5})
.then(function(contr){
contract_att.bulkCreate([{'contracts_id':contr.id_contracts, 'rate_id':2},{'contracts_id':contr.id_contracts,'rate_id':3}]);
});
If you have another solution, pls share ))
There are several issues here
you said Contract > 1:M > Contract_attach then you write Contract_attach.hasMany(Contract...etc. it should be the other way around Contract.hasMany(Contract_attach...etc same goes for rates
In diagram there is relation between Contract_attach and rates but the define you didn't define this reference
Its not clear that columns rate_id and contract_id are nullable or not. based on that we can define if Contract_attach can or can not be belong to 2 different tables.
I think that the database schema need to change or explain why its in this way

Sequelize association generate fields that do no exists

I'm converting a PHP API to a GraphQL api. I'm using Sequelize as ORM package. I have two tables that I want to couple via a hasOne connection.
This is my AdvisoryService model:
module.exports = function(sequelize, DataTypes) {
const AdvisoryService = sequelize.define(
'advisoryService',
{
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
field: 'id',
},
country: {
type: DataTypes.INTEGER(11),
allowNull: true,
references: {
model: 'system_country',
key: 'id',
},
field: 'country',
},
//REDACTED
},
{
tableName: 'advisory_service',
timestamps: false,
},
)
AdvisoryService.associate = models => {
AdvisoryService.hasOne(models.systemCountry, {
as: 'Country',
foreignKey: 'country',
})
}
return AdvisoryService
}
And my systemCountry model:
/* jshint indent: 2 */
module.exports = function(sequelize, DataTypes) {
return sequelize.define(
'systemCountry',
{
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
field: 'id',
},
oldId: {
type: DataTypes.INTEGER(11),
allowNull: true,
unique: true,
field: 'old_id',
},
subcontinentId: {
type: DataTypes.INTEGER(11),
allowNull: true,
references: {
model: 'system_subcontinent',
key: 'id',
},
field: 'subcontinent_id',
},
code: {
type: DataTypes.STRING(2),
allowNull: false,
field: 'code',
},
longCode: {
type: DataTypes.STRING(3),
allowNull: false,
field: 'long_code',
},
currency: {
type: DataTypes.STRING(255),
allowNull: true,
field: 'currency',
},
currencyCode: {
type: DataTypes.STRING(255),
allowNull: true,
field: 'currency_code',
},
isEu: {
type: DataTypes.INTEGER(1),
allowNull: false,
field: 'is_eu',
},
isAsean: {
type: DataTypes.INTEGER(1),
allowNull: false,
field: 'is_asean',
},
isFragileWb: {
type: DataTypes.INTEGER(1),
allowNull: false,
field: 'is_fragile_wb',
},
isFragilePf: {
type: DataTypes.INTEGER(1),
allowNull: false,
field: 'is_fragile_pf',
},
isFragileOecd: {
type: DataTypes.INTEGER(1),
allowNull: false,
field: 'is_fragile_oecd',
},
title: {
type: DataTypes.STRING(255),
allowNull: false,
field: 'title',
},
latitude: {
type: 'DOUBLE',
allowNull: true,
field: 'latitude',
},
longitude: {
type: 'DOUBLE',
allowNull: true,
field: 'longitude',
},
},
{
tableName: 'system_country',
timestamps: false,
},
)
}
It generates the following query:
Executing (default): SELECT `id`, `old_id` AS `oldId`, `subcontinent_id` AS `subcontinentId`, `code`, `long_code` AS `longCode`, `currency`, `currency_code` AS `currencyCode`, `is_eu` AS `isEu`, `is_asean` AS `isAsean`, `is_fragile_wb` AS `isFragileWb`, `is_fragile_pf` AS `isFragilePf`, `is_fragile_oecd` AS `isFragileOecd`, `title`, `latitude`, `longitude`, `country` FROM `system_country` AS `systemCountry` WHERE `systemCountry`.`country` = 1 LIMIT 1;
And throws the following error: SequelizeDatabaseError: Unknown column 'country' in 'field list'. Which I get, because there is no county field in the system_country table. I don't know why the association generates the country field. Can someone point out what I'm doing wrong?
You relation -
AdvisoryService.associate = models => {
AdvisoryService.hasOne(models.systemCountry, {
as: 'Country',
foreignKey: 'country',
})
}
Is defining the relationship with key - country hence its finding country in systemCountry table
Use the Following object in your relation definition -
{as: "Country", foreignKey: "OtherTableColumn", sourceKey: "SameTableColumn"}

sequelize - inner join gives an error after added a foreign key

i have these 2 models:
module.exports = function(sequelize, DataTypes) {
return sequelize.define('services_prices', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true
},
service_id: {
type: DataTypes.INTEGER(11),
allowNull: true,
references: {
model: 'services',
key: 'id'
}
},
created_at: {
type: DataTypes.DATE,
allowNull: false
},
limit: {
type: DataTypes.INTEGER(11),
allowNull: true
},
price: {
type: DataTypes.INTEGER(11),
allowNull: true
}
});
};
which is parent of this model: (services_user_prices can override services_prices )
module.exports = function(sequelize, DataTypes) {
return sequelize.define('services_user_prices', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
user_id: {
type: DataTypes.INTEGER(11),
allowNull: true
},
created_at: {
type: DataTypes.DATE,
allowNull: false
},
currency: {
type: DataTypes.STRING(255),
allowNull: true
},
is_active: {
type: DataTypes.INTEGER(1),
allowNull: true,
defaultValue: '0'
},
is_trial: {
type: DataTypes.INTEGER(1),
allowNull: true,
defaultValue: '0'
},
start_date: {
type: DataTypes.DATE,
allowNull: false
},
end_date: {
type: DataTypes.DATE,
allowNull: true
},
price: {
type: DataTypes.INTEGER(11),
allowNull: true
},
bundle_price_id: {
type: DataTypes.INTEGER(11),
allowNull: true,
references: {
model: 'services_prices',
key: 'id'
}
}
});
};
when trying to join them i get an error:
EagerLoadingError: services_prices is not associated to services_user_prices!
const result= await db.services_user_prices.findOne({
where: { is_active: 1, user_id: 123 }, include:[{db.services_prices}]
});
in the db services_user_prices has foreign key to services_prices table
what am i doing wrong?
Well if you are using sequelize then you need to update your model because
by default, sequelize will be looking for foreign key starts with model name like
you have defined bundle_price_id as a foreign key for services_prices.
You need to change your column name to services_price_id then it will get fixed.
or if you want to use bundle_price_id you need to define it in your model relation as.
Model.belongsTo(models.ModelName, { foreignKey: 'your_key'} )
Please feel free if you need to ask anything else.
As complement of the above answer you need to add an identifier with as: on the association like this:
Model.belongsTo(models.ModelName, { foreignKey: 'your_key', as:'your_identifier' } )
Then when you do the include on the method you also call the identifier:
await db.services_user_prices.findOne({
where: { is_active: 1, user_id: 123 },
include:[{
model: db.services_prices
as: 'your_identifier'
}]
});
If you don't define the foreignKey field, the as field will set the column name.

Resources