How to make query with order by with current date - mysql

I want to join 2 tables and want to show latest post first based on current date for example today's publish post will show at top then future date then past date's post will show. I need to write this query in sequelize. I am getting unknown column error 'postModel.DATE(published_at)' My sequelize query is like that -
postModel.findAndCountAll({
include:[
{ model:userModel,
where: { user_id: user_id},
required:false
},
],
order: [
[ 'DATE(published_at) = DATE(NOW())', 'DESC']
],
limit: limit,
offset: offset,
});
Following raw query is working well to me
SELECT * FROM posts as P JOIN user as U ON U.id = P.user_id
where
ORDER BY
DATE(P.published_at)=DATE(NOW()) DESC,
DATE(P.published_at)<DATE(NOW()) DESC,
DATE(P.published_at)>DATE(NOW()) ASC`

remove your date function and query like this .
postModel.findAndCountAll({
include: [{ model: userModel, where: { user_id: user_id },required:false }],
where: {
published_at: {
[Op.eq]: Date(NOW()),
},
},
order: [["published_at", "DESC"]],
limit: limit,
offset: offset,
});

Related

Node Sequelize with Mysql order by, need 0 values to be last

Here I'm trying to order the result using a filed order_no, the default value for order_no is 0. I have to sort the values to get the desired output like 1,2,3,0,0,0. I tried the below options in findAll() in sequelize but not working it is returning 0 values first.
let options = {
attributes: [[Sequelize.fn('DISTINCT',
Sequelize.col('user_id')),
'user_id'],
'order_no'],
raw: true,
where: {},
limit: limit,
offset: offset,
order: [[Sequelize.fn('isnull',
Sequelize.col('order_no'))],
[Sequelize.literal('order_no'),
'ASC']]
};
You can use IS_NULL and IF functions to achieve such sorting:
order: [Sequelize.fn('IS_NULL',
Sequelize.fn('IF',
Sequelize.literal('order_no=0'),
null,
Sequelize.col('order_no')
)
),
'order_no'
]

Sequelize order and limit data by 10 after getting all result

// returnJson: false,
model: Organization,
where: where,
limit: 10,
offset: 0,
order: [[{ model: Events }, "name", "desc"]],
include: [
{
model: Events,
through: { model: Organization_Event },
...softDeleteFilter,
},
],
});
**Organization can be linked to multiple events and vice versa. **
I want to order and limit data code is working fine. But when I apply for the order by asc or desc It orders the rows from the first 10 results.
I am expecting the following result:-
first to get all data and then apply the order after that return 10 result on database level
database: mysql

How to fetch a serial number from a mysql table using Sequelize in nodeJS?

I have a mysql Query:-
SELECT #a:=#a+1 serial_number,rule FROM pledges,(SELECT #a:= 0) AS a;
This gives me a serial number along with the rule from the table.
How can I do that in Sequelize?
This is the query I wrote in the model which gives me id and rule:-
Pledge.getPledgeList = function(lang_code='EN') {
return this.findAll({
attributes:['id','rule'],
where: {
status:'a',
deleted_at:null
},
include:[
{ association: 'local', where: {lang_code:lang_code} ,required: false},
]
})
}

Change Alias of Distinct for sequelize

I am using below query on my code that is
await to( mymodel.aggregate('cid', 'DISTINCT', {plain: false,where:{created_by:user.id}}));
and query out put on console is
SELECT DISTINCT(`cid`) AS `DISTINCT` FROM `mymodel` AS `mymodel` WHERE `mymodel`.`created_by` = 7;
I got below output that is
ids --------------- [ { DISTINCT: 9 }, { DISTINCT: 10 }, { DISTINCT: 11 } ]
I want to change the alias that is DISTINCT to id. How i do that like below
ids --------------- [ { id: 9 }, { id: 10 }, { id: 11 } ]
I don't think .aggregate() supports aliasing fields however it's simple to turn this into a regular query instead.
await mymodel.findAll({
attributes: [ [ Sequelize.fn('DISTINCT', 'cid'), 'id' ] ],
where: { created_by: user.id }
});
Here we're utilising Sequelize.fn() to create the DISTINCT on cid and using the array attribute notation to alias it to id. More info on this here.

Sequelize - Limiting and ordering inside include

I have associated 3 tables in Sequelize.
Using findOne am trying to retrieve one room with all messages limited to 10 and with order by message_timestamp but to no avail.
models.Room.findOne({
where: {
room_id: room_id
},
include: [ {
model: models.Message,
limit: 10,
offset: 0,
order: 'message_timestamp DESC'
} ] })
The above code retrieves all the messages (not limited to 10) and are not ordered according to message_timestamp.
Is there a solution? How can I go about doing this?
Thank You.
You cannot limit in an includes statement in sequelize. You can only limit from the top-level. With this in mind, you can try something like this:
models.Message.findAll({
include [{
model: models.Room,
where: { room_id: room_id }
}]
limit: 10,
offset: 0,
order: 'message_timestamp DESC'
})
Since includes are INNER JOINs, it will only retrieve messages where the associated room_id = room_id