Counting number of associated rows in sequelize - node.js

I am trying to find the count of students inside the classStudents association. Here teacher_details table is connected to class_details tables using 'section'
association and class_details tables is connected to student_details table using 'classStudents' association. I have tried the below method but got error ==>
Unknown column 'section->classStudents.studentId' in 'field list'
please let me know the correct procedure to count the associated students count
const getAssignedDetails = async (req, res) => {
try {
const assignedDetails = await Entity.teacherAssignedDetail.findAll({
where: { status: 1, teacherId: req.teacherId },
attributes: [
'role',
[
Sequelize.fn(
'COUNT',
Sequelize.col('section.classStudents.studentId')
),
'studentCount',
],
],
include: [
{
association: 'section',
attributes: ['sectionId', 'className', 'classEmoji'],
include: [
{
association: 'classStudents',
where: { status: 1 },
required: false,
},
],
where: { status: 1 },
},
{
association: 'subjectDetails',
attributes: [['id', 'masterSubjectId'], 'subjectName'],
},
],
});
res.json({
responseCode: 0,
responseMessage: 'Success',
responseData: assignedDetails,
});
} catch (err) {
res.status(500).send(errorHandling(err.message));
}
};

Related

I can't use session in nodejs. how can i make safe listing?

In my project that I created using nextjs, I want the session to list while I make a listing query on the backend. If there is no session, I want it not to give authorized permission. I am using next authentication. I can't pull next in session But I can't get session. Can you help me, please?
Offers.belongsTo(Users, {as: 'User', foreignKey: 'user_id'});
router.post('/api/logistic/offers/get-offers', async (req, res) => {
const {limit, page, sortColumn, sortType, search, session} = req.body;
if(session){
const total = await Offers.findAll();
const offersList = await Offers.findAll({
limit: limit,
offset: (page - 1) * limit,
order: [
[sortColumn, sortType]
],
where: {
[Op.or]: [
{
offers_no: {
[Op.substring]: [
search
]
}
},
{
agreement_date: {
[Op.substring]: [
search
]
}
},
{
routes: {
[Op.substring]: [
search
]
}
},
{
type_of_the_transport: {
[Op.substring]: [
search
]
}
},
]
},
include: [{
model: Users,
as: 'User'
}]
});
res.json({
total: total.length,
data: offersList
});
}else {
res.status(401).send(JSON.stringify({
status: "error",
title: 'Unauthorized',
message: 'Unauthorized'
}));
}
})
The error I get in the terminal is always like this. I can't use session
//offers list
Offers.belongsTo(Users, {as: 'User', foreignKey: 'user_id'});
router.post('/api/logistic/offers/get-offers', async (req, res) => {
const session = await getSession({req});
console.log(session);
if(session){
const {limit, page, sortColumn, sortType, search} = req.body;
const total = await Offers.findAll();
const offersList = await Offers.findAll({
limit: limit,
offset: (page - 1) * limit,
order: [
[sortColumn, sortType]
],
where: {
[Op.or]: [
{
offers_no: {
[Op.substring]: [
search
]
}
},
{
agreement_date: {
[Op.substring]: [
search
]
}
},
{
routes: {
[Op.substring]: [
search
]
}
},
{
type_of_the_transport: {
[Op.substring]: [
search
]
}
},
]
},
include: [{
model: Users,
as: 'User'
}]
});
res.json({
total: total.length,
data: offersList
});
}else {
res.status(401).send(JSON.stringify({
status: "error",
title: 'Unauthorized',
message: 'Unauthorized'
}));
}
})
This is how my code was before. but it didn't work.

complicated query using sequelize

i have 3 tables .. profile, player, garage
profile has winCount , loseCount
player has username
garage has carNumber
they are all connected with each other using the id from player table (playerId in table garage and profile)
i want to get the
top 20 winCount , username , carnumber
i am trying this code
let racers = await Profile.findAll({
where: {
carRaceWinCount: {
[Op.gt]: 0
}
},
limit: 20,
order: [
['carRaceWinCount', 'DESC']
]
})
.then((races: any) => {
Garage.findAll({
where: {
playerId: races.id
},
attributes : ['carNum']
})
Player.findAll({
where :{
id : races.id
},
attributes : ['username']
})
})
and it is not working
what is the best way to get this query
If you have these associations:
Player.hasMany(Profile, { foreignKey: 'playerId' })
Player.hasMany(Garage, { foreignKey: 'playerId' })
Profile.belongsTo(Player, { foreignKey: 'playerId' })
then the query might look like this
await Profile.findAll({
where: {
winCount: {
[Op.gt]: 0
}
},
limit: 20,
include: [{
model: Player,
include: [{
model: Garage,
// this is important option to query all garames as separate queries, Otherwise you will get wrong count of profiles.
separate: true
}]
}]
order: [
['winCount', 'DESC']
]
})

join same table in sequelize and print in excel

I want to print parent name in excel
this is my code
function getReportT0Print(req, res) {
return new Promise((resolve, reject) => {
Product.findAll({
where: {
$and: [
{
public: true,
visible: true,
ancestry: {
$not: null,
},
},
],
},
include: [
{
model: ormDb.Document,
required: false,
},
],
attributes: ["name", "slug", "folder_path"],
})
.then(function (data) {
// console.log("data" + data.length);
var rows = [];
rows.push(["Product Name", "Slug", "File Path", "Product Parent Name"]);
data.map(function (product) {
rows.push([
product.name,
product.slug,
product.folder_path,
(here i need to print parent name)
]);
});
var workbook = new Excel.Workbook();
var sheet = workbook.addWorksheet("products_with_tags");
sheet.addRows(rows);
resolve(workbook);
return res.send("successfull");
})
.catch(function (err) {
reject(err);
});
});
}
i can print name, slug,folder_path but i don't know how to print parent name in excel file
as parent name is not present but i have given parent_id in place of parent name and want to print parent name
my SQl table look like this
("id" "name" "version" "published" "reviewed" "visible" "public", "parent_id")
You need to register an association between two Product models like this:
Product.belongsTo(Product, { foreignKey: 'parent_id', as: 'parent' });
You can place it in some module outside model's module file where you create Sequelize instance, for example.
To use this association you need to use the same include option as you did with Document:
Product.findAll({
where: {
$and: [
{
public: true,
visible: true,
ancestry: {
$not: null,
},
},
],
},
include: [
{
model: Product,
as: 'parent',
required: false, // or true if parent_id is required field
// or you wish to get all products with parents
attributes: ["name", "slug", "folder_path"],
},
{
model: ormDb.Document,
required: false,
},
],
attributes: ["name", "slug", "folder_path"],
})

How can I show include model's specific column in an array? Sequelize PostgreSQL

I have two models which are Licences and Items.
models.Licences.hasMany(models.Items, {
foreignKey: 'licenceId',
onDelete: 'CASCADE',
});
Licence can has many Items.
Items model has licenceId and description.
try {
return await db.Licences.findAll({
order: [['createdAt', 'DESC']],
attributes: [
'id',
'desc',
'version',
[db.Sequelize.col('Items.description'), 'itemDesc']
],
include: [
{
model: db.Items,
attributes: []
},
],
});
} catch (error) {
throw error;
}
}
This method return only one item description. However I want to return response as;
[
{
id: 1,
desc: 'LicenceOne',
itemDesc: [
"exone",
"extwo"
]
}
]
How can I do this?
You can try the below way and make changes.
try {
return await db.Licences.findAll({
order: [['createdAt', 'DESC']],
attributes: [
'id',
'desc',
'version',
],
include: [
{
model: db.Items,
attributes: ['description'],
},
],
});
} catch (error) {
throw error;
}
}
But you will get the below output. Not exactly how you want but you can reprocess all array object and have all description as a array of string in each object. Sequelize will not automatically process the array directly as per what I know.
[
{
id: 1,
desc: 'LicenceOne'
version: '1.1.1',
Items: [
{
description: 'the desctiption 1'
},
{
description: 'the desctiption 2'
},
{
description: 'the desctiption 3'
},
]
},
{
id: 2,
// and on...
}
]

how to merge response attributes of other table in node js

I have 3 Tables User, Cars and UserCars
User{id, name, phone, email}
Cars{id, name, manufacturer}
UserCars{id, car_id, user_id, role}
User have many cars(through UserCars)
Cars have many users(through UserCars)
I am using express js
router.get('/', async (req, res) => {
try {
let car = await Car.findOne({
where: {
id: req.car_id
}});
let users = await car.getUsers({joinTableAttributes: ['role']})
res.send(users)
} catch (e) {
console.log(e)
res.status(400).send(e)
}
})
and this my response
[
{
"id": 1,
"name": "test",
"email": null,
"phone": null,
"createdAt": "2019-07-09T09:38:11.859Z",
"updatedAt": "2019-07-12T04:34:20.922Z",
"User_car": {
"role": "driver"
}
}
]
but any idea how to include role in the user object, rather then specifying it separately in User_car table,
Is there a way where i can get the below output
[
{
"id": 1,
"name": "test",
"email": null,
"phone": null,
"role": 'driver'
"createdAt": "2019-07-09T09:38:11.859Z",
"updatedAt": "2019-07-12T04:34:20.922Z"
}
]
You can use sequelize.literal to get that field when getting your attributes.
attributtes: [
// define your other fields
[sequelize.literal('`users->User_car`.`role`'), 'role'],
]
Now, I not sure if that is going to work with car.getUsers. I usually do a single query with include and also define the "join" table so I can know how is name it on sequelize. Let me show you an example.
module.exports = (sequelize, DataTypes) => {
const UserCar = sequelize.define('UserCar', {
// id you don't need and id field because this is a N:M relation
role: {
type: DataTypes.STRING
},
carId: {
field: 'car_id',
type: DataTypes.INTEGER
},
userId: {
field: 'user_id',
type: DataTypes.INTEGER
},
}, {
tableName: 'User_car',
underscored: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
});
UserCar.associate = (models) => {
models.user.belongsToMany(models.car, { as: 'cars', through: User_car, foreignKey: 'user_id' });
models.car.belongsToMany(models.user, { as: 'users', through: User_car, foreignKey: 'car_id' });
};
return UserCar;
};
router.get('/', async (req, res) => {
try {
const users = await User.findAll({
include: [{
model: Car,
as: 'cars',
where: { id: req.car_id }
}],
attributtes: [
'id',
'name',
'email',
'phone',
[sequelize.literal('`cars->User_car`.`role`'), 'role'],
]
})
res.send(users)
} catch (e) {
console.log(e)
res.status(400).send(e)
}
});

Resources