How to write a count like this in Sequelize? - node.js

SELECT COUNT(id), age FROM `red_cross_volunteers` GROUP BY age;

Simply use Sequelize.fn in attributes option and group option while calling findAll:
const stats = await RedCrossVolunteers.findAll({
attributes: [[Sequelize.fn('COUNT', Sequelize.col('id')), 'age_count'], 'age'],
group: ['age']
})

Related

Need a sequelize alternative to a find raw query

SELECT * FROM recommended_plan WHERE user_id = ? AND created_at = (SELECT MAX(created_at) FROM recommended_plan WHERE user_id = ?)
I am stuck at converting this raw query into a sequelize one.
CASE 1 - you have only one record with max created_at value
First you can convert it to this equivalent one:
SELECT * FROM recommended_plan WHERE user_id = ?
order by created_at desc
limit 1
(Please pay attention that the limit option depends on a certain DBMS and could have a different name and/or syntax).
Now you can easily construct the corresponding Sequelize query:
const plan = await RecommendedPlan.findAll({
where: {
user_id: userId
},
limit: 1,
order: [['created_at', 'desc']]
})
CASE 2 - you have several records with max created_at value:
You can use Sequelize.literal to use a condition with a subquery:
const plan = await RecommendedPlan.findAll({
where: {
user_id: userId,
created_at: Sequelize.literal('(SELECT MAX(created_at) FROM recommended_plan rp WHERE rp.user_id = $userId)')
},
bind: {
userId: userId
}
})

Is there a way I can use Group By and Count with Type Orm Repository

I am new here recently joined and New in Type ORM My code that I am trying
FIRST QUERY: I would like to use this approach but not sure how I can group by with count on the column and then order by desc on that column
const result = await this.jobViewsRepository.find({
relations: ["jobs"],
loadEagerRelations: true,
order: { id: "DESC" },
skip: offset,
take: limit,
}
);
I am trying if I can use this in my above query
SECOND QUERY: IT'S WORKING FOR ME PERFECTLY THE RESULT I AM LOOKING
const res = await this.jobViewsRepository.createQueryBuilder('jobViews')
.addSelect("COUNT(jobViews.user_id) AS jobViews_total_count" )
.leftJoinAndSelect(Jobs, "jobs", "jobs.id = jobViews.job_id")
.where("jobs.user_id != :id", { id: user_id })
.groupBy("jobViews.job_id")**
.orderBy('jobViews_total_count', 'DESC')**
.limit(limit)
.offset(offset)
.getRawMany();
Please if any can help me out in this will be really appreciated
Thanks
At least in the current version there is no way to do this feature (neither in the documentation nor in the web)
I believe you can use .query to write your own query
Now is the only one way is to use queryBuilder And .groupBy("user.id") with .addGroupBy("user.id")
https://orkhan.gitbook.io/typeorm/docs/select-query-builder#adding-group-by-expression
Or write raw query:
import { getManager } from 'typeorm';
const entityManager = getManager();
const someQuery = await entityManager.query(`
SELECT
fw."X",
fw."Y",
ew.*
FROM "table1" as fw
JOIN "table2" as ew
ON fw."X" = $1 AND ew.id = fw."Y";
`, [param1]);
you use findAndCount to count the result size
result = await this.jobViewsRepository.findAndCount({ ... })
the result = [data,count]

aggregate function in sequelize

i need a query which has aggregate function in include. i want to get count of ticket sell in each events
i tried code below
const data = await Items.paginate({
page: offset.value,
paginate: limit.value,
where: itemType,
include:[
{model:ItemTypes},
{model:ItemPayment,
attributes: [[db.sequelize.fn('sum', db.sequelize.col('ItemPayments.numberOfTickets')), 'total']],
group: ["ItemPayments.itemId"],
}],
raw:true
});
but it gives me an error like below
In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'Items.id'; this is incompatible with sql_mode=only_full_group_by
Add separate : true and try to execute the query again
{
model:ItemPayment,
attributes: [[db.sequelize.fn('sum', db.sequelize.col('ItemPayments.numberOfTickets')), 'total']],
group: ["ItemPayments.itemId"],
separate : true // <--------- HERE
}

Prisma: use count inside a mutation resolver

I have a mutation createPet and want it to throw an error if the user already has 5 pets created.
I was thinking that something like this will work but it doesn't:
const petsCount = await db.pets({
where: { owner: user.id },
}).count();
I also didn't find anything in the docs
To retrieve a count, you can use Aggregations:
const petsCount = await prisma
.petsConnection({where: {owner: user.id}})
.aggregate()
.count()
Source: documentation

How to clone/copy instance item/row in sequelize

I tried to find a way to copy/clone instances in Sequelize but without success. Is there any way to do it with a built-in function or without? What I want is to simply copy rows in the database and the new item should have only a different id.
There is no such direct function for that , What you can do is :
Fetch the object that you want to clone/copy
Remove Primary Key from it
Make a new entry from it
model.findOne({ //<---------- 1
where : { id : 1 } ,
raw : true })
.then(data => {
delete data.id; //<---------- 2
model.create(data); //<---------- 3
})
As said, there is no such direct function for that (thanks Vivek)
If you find useful, place the following code on your model class:
async clone() {
let cData = await THISISMYMODEL.findOne({
where: { id: this.id},
raw: true,
});
delete cData.id;
return await THISISMYMODEL.create(data);
}
Take into account that "THISISMYMODEL" should be the model class defined and "id" the primary key attribute used.
Also take into account the use of Foreign Keys (relations with other models), it will use the same keys. Otherwise you should clone those instances too.
You may need to update the name though or some other field to identify it as a copy,
const data = await model.findOne({ where: {id: 1}, raw: true, attributes: { exclude: ['id'] } });
data.name = data.name + '(copy)';
const newRecord = await model.create(data);
Write a Model.create(data) function inside Model.js and call this function from inside of a loop, as many times you need it will create the copy of the same data.

Resources