I have such query
const companiesByEmployeesOfProdUnits = await models.CompanyProductionUnitNonCeased
.findAll({
raw: true,
limit: 5,
offset: 0,
attributes: [[sequelize.fn('DISTINCT', sequelize.col('company_id')), 'company_id']],
include: [{
model: models.ProductionUnitCore,
as: 'production_unit',
include: [{
model: models.EmployeeInformationProductUnit,
as: 'employee_information_product_units',
attributes: ['number_of_employees'],
where: { is_current: true, ...rangeOfEmployees }
}]
}]
})
There are more then 2 million records. How can I get 5 records? Because now I have only one but I'm sure about correct where conditions and I don't understand why I get only one instead of 5.
I need only to add 'required: true' field for each 'include' object
Related
I am trying to findAll records included nested tables, but did not understand how could I filter included tables by where clause. Here are the words:
const players = await PlayerService.findPlayers({
attributes: { exclude: ['password'] },
include: [
{ all: true },
{
model: Team,
as: 'captainTeams',
attributes: {exclude: ['createdAt', 'updatedAt']}
},
{
model: Team,
as: 'teams',
where: { type: 1 },
required: true,
through: {attributes: []},
attributes: {exclude: ['createdAt', 'updatedAt']}
}
]
})
Here is the result:
If I delete where and required from including Team clause, here is the result:
I would like to filter teams.type=2. Could you help me ?
I'm newbie for Sequelize
I have a problem with "Nested Eager Loading"
I have 2 Table with 1-to-many relationship
Comment Table
User Table
I use this code for the query
Comment.findAll({
include: [User]
})
I got
{
id: 1,
comment: "test",
user: {
id: 3,
name: "someone"
}
}
But I expected result like this
{
id: 1,
comment: "test",
user_id: 3,
user_name: "someone"
}
I read several stackoverflow post it has a solution but work for version 3.3
Comment.findAll({
attributes: ['id', 'name', ['user.id','user_id'], ['user.name','user_name']]
include: [{ model: User, attributes:[], nested: false, required: true }]
})
Comment.findAll({
attributes: ['id', 'name', [Sequelize.col('user.id'),'user_id'], [Sequelize.col('user.name'),'user_name']]
include: [{ model: User, attributes:[], nested: false, required: true }]
})
but it's not work for me.
now I use sequelize 5.5.1 how can I implement it.
Can someone help me, please?
You can use this code to get the desired output:
Since Sequelize is promised based , it is recommend to use then and catch.
Comment.findAll({
include: [User]
}).then(result=>
{
let obj=
{
id: result.item,
comment: result.comment,
user_id: result.user.id,
user_name: result.user.name
};
console.log(JSON.stringify(obj));
}).catch(err=>
{
console.log(err);
});
I have a query that looks like this:
return GroupMember.findOne({
where: { gid: gid, member_id: uid },
include: [
{
model: User,
as: 'member',
attributes: ['display_name'],
},
{
model: Group,
as: 'group',
attributes: ['name'],
}
]
});
So, for the "member" relation, I am requesting only the 'display_name" column. However, the User model has 3 virtual columns declared in it, and they are always present in the query result even though I asked for only 'display_name'. How do I prevent the virtual columns from being present in the result?
So for excluding virtual columns, you have to use the exclude property the attributes field, so the new query should be like this
return GroupMember.findOne({
where: { gid: gid, member_id: uid },
include: [
{
model: User,
as: 'member',
attributes: { include: ['display_name'], exclude: ['virtual_columne_name1', 'virtual_columne_name2', 'virtual_columne_name3']},
},
{
model: Group,
as: 'group',
attributes: ['name'],
}
]
});
So, I have an existing MySQL database that I'm trying to connect to with Sequelize in Node that has a products table, a categories table and a categories_products table. What I want to do is return products, with each product containing all of the categories it belongs to. Here's what I've got:
// Declare Product Model
const Product = sequelize.define('products', {
name: Sequelize.STRING,
description: Sequelize.STRING,
single_price: Sequelize.BOOLEAN,
oz_price: Sequelize.FLOAT,
half_price: Sequelize.FLOAT,
quarter_price: Sequelize.FLOAT,
eigth_price: Sequelize.FLOAT,
gram_price: Sequelize.FLOAT,
unit_price: Sequelize.FLOAT
},
{
underscored: true
});
// Declare Category Model
const Category = sequelize.define('categories', {
name: Sequelize.STRING,
parent_id: Sequelize.INTEGER,
picture_file_name: Sequelize.STRING
},
{
underscored: true
});
// Join Table
const ProductCategory = sequelize.define('categories_products', {
product_id: Sequelize.INTEGER,
category_id: Sequelize.INTEGER,
}, {
timestamps: false,
underscored: true
});
// Do this because there is no id column on ProductCategory table
ProductCategory.removeAttribute('id');
Category.hasMany(Category, { as: 'children', foreignKey: 'parent_id' });
ProductCategory.belongsTo(Product);
ProductCategory.belongsTo(Category);
Product.hasMany(ProductCategory);
Category.hasMany(ProductCategory);
Using this setup, I query as follows:
Product.findAll({
include: [{
model: ProductCategory,
include: [ Category ]
}],
where: { active: true },
limit: 10
}).then(prods => {
res.send(prods);
}).catch(err => {
res.status(500).send(err);
});
I get back my products and each one has an array of categories, BUT each product only shows a max of one category. I have products that should have many categories, but it only shows the first.
Am I missing something? Any help would be greatly appreciated.
I think you should use belongsToMany association here.
You can define association like this
Product.belongsToMany(Category, { through: ProductCategory, foreignKey: 'product_id' });
Category.belongsToMany(Product, { through: ProductCategory, foreignKey: 'category_id' });
and the query can be
Product.findAll({
include: [Category]
}).then((res) => {
console.log(res);
})
Though the questioner might have gotten the solution but I ran into this composite key table problem and this is the solution with code example. Notice the "through" keyword. That is what solves the association where you want to limit your findings to say a category as AbhinavD asked above. Your category id would go in the literal expression. Applies to findAll too.
const products = await Product.findAndCountAll({
include: [Category],
through: { where: { category_id: `${category_id}` } },
attributes: [
'product_id',
'name',
],
limit: limitPage,
offset: offsett,
});
Is there a way to find models by a condition that applies to its own field or to its association's field?
Given models Model and Association, where each Model has one Association.
const Model = sequelize.define('model', {
name: sequelize.STRING,
});
const Association = sequelize.define('association', {
name: sequelize.STRING,
});
Association.belongsTo(Model);
Model.hasOne(Association);
I want to find all Models, that either has a name equal to "text", or has an Association with a name equal to "text".
So far I come up with the solution with Sequelize.literal, that doesn't look robust enough.
Model.findAll({
attributes: ['id', 'name'],
include: [{
model: Association,
attributes: [],
}],
where: {
$or: [
{ name: 'test' },
Sequelize.literal('association.name = \'test\''),
],
},
});
Is there a better way?
This feature is described in the docs: Top level where with eagerly loaded models.
Model.findAll({
attributes: ['id', 'name'],
include: [{
model: Association,
attributes: [],
}],
where: {
$or: [
{ name: 'test' },
{ '$association.name$': 'test' },
],
},
});