I am trying to do query to get all rows between id 1 to 4.
I am using mySQL and sequelize.
query
`
main.test = function(req,res,next)
{
var param = req.params;
model.Time.find({
where:{
id:{
$between:[1,4]
}
},limit: 10
}).then(function (time) {
console.log("Time"+time);
});
}
`
and getting the result when execute
Need a way solve it?
Related
Mysql Query :
SELECT
* FROM
advisor_product_range WHERE 5 BETWEEN from_range AND to_range;
How to replicate the same in sequelize format
const AdvisorProductRangeDataGdp = await AdvisorProductRange.findAll({
attributes: ['office_id','yyyymmdd','product_type','from_range','to_range','amount_per_order'],
where: {
from_range: {
[dbOp.gte]: gdpCount
},
to_range: {
[dbOp.lte]: gdpCount
}
}
});
OUTPUT OF THIS QUERY IN MYSQL TERMS :
> SELECT `office_id`, `yyyymmdd`, `product_type`, `from_range`,
> `to_range`, `amount_per_order` FROM `advisor_product_range` AS
> `AdvisorProductRange` WHERE `AdvisorProductRange`.`from_range` <= 5 AND
> `AdvisorProductRange`.`to_range` >= 5;
Mysql Table Structure :
Version : sequelize :5.8
Issue was found out its was related to the operator used in the query
was switch in the incorrect way .
const AdvisorProductRangeDataGdp = await AdvisorProductRange.findAll({
attributes: ['office_id','yyyymmdd','product_type','from_range','to_range','amount_per_order'],
where: {
from_range: {
[dbOp.lte]: gdpCount
},
to_range: {
[dbOp.gte]: gdpCount
}
}
});
I just confuse with this case. I've been try to make sure the time zone in MySql and see the data that out from Date(Date.now()). That's all is correct with my timezone. But when i try to input the data to MySql, and i check in my Database. The time zone is wrong and different with my Time zone. Is there anyone can help me ?
This my code
const Employee = require('../models/employee');
const History = require('../models/history');
async createHistory(employee){
let result;
try {
const checkData = await Employee.findOne({where :
{employeeId : employee.employeeId}
});
if(checkData !== null){
const createData = await History.create({
employeeId : employee.employeeId,
in : Date(Date.now())
});
console.log(date.toLocaleString());
console.log('True')
}else {
result = {message : false}
}
} catch (e) {
logEvent.emit('APP_ERROR',{
logTitle: '[CREATE-HISTORY-ERROR]',
logMessage: e
});
}
return result;
}
The Time in field 'in' is wrong, it should be 14:43
I just get the answer,
The answer is .. because i using Sequelize to store the data to MySql i have to input the time zone in my connection.
Here my code :
const connection = new Sequelize(
{
timezone: "+07:00"
}
);
Is there a way to check if a particular string exists in a column in a table?
For example, I have a table 'fruits' with two columns, primary key and fruit_name and following rows
1 apple
2 orange
3 pineapple
I have a sample string named apple_shake. I need to check if a substring of this apple_shake exists. The query should return row containing 'apple'
I know how this can be done in mysql query - SQL - Query to find if a string contains part of the value in Column
But through sequelize, following has problem
var sample_fruit_string = "apple_shake";
var gsp_config = await model.fruit.findOne({where: {
fruit_name: {
[Op.like]: sample_fruit_string + '%'
}
}});
Credit to #alx for the SQL I didn't know was possible - this is how you generate the appropriate SQL with Sequelize. Note that this may not be efficient with large datasets.
const sample_fruit_string = "apple_shake";
const gsp_config = await model.fruit.findOne({
attributes: ['id'],
where: Sequelize.where(
Sequelize.fn('LOCATE', Sequelize.col('fruit_name'), sample_fruit_string),
Sequelize.Op.ne,
0
),
logging: true,
});
Generates the following:
SELECT `id` FROM `fruit` AS `fruit` WHERE LOCATE(`fruit_name`, 'apple_shake') != 0 LIMIT 1;
Sequelize has a substring operator which you could use directly to solve this.
var sample_fruit_string = "apple_shake";
var gsp_config = await model.fruit.findOne({where: {
fruit_name: {
[Op.substring]: sample_fruit_string // LIKE '%sample_fruit_string%'
}
}});
var sample_fruit_string = "apple_shake";
var gsp_config = await model.fruit.findOne({where: {
fruit_name: {
[Op.like]: `%${sample_fruit_string}%` // LIKE '%sample_fruit_string%'
// [Op.ilike]: `%${sample_fruit_string}%` // For case sensitive searching
// [Op.substring]: sample_fruit_substring // Has been depreciated in future version of sequelize.
}
}});
Promise.all(sendData.franchisee.map(row => {
return knex('designer.settings').select('value').where({setting_key : 'PRICING_TIER'})
.then(pricing_tier => {
row.pricing_tier = pricing_tier[0].value;
knex('designer.pricing_tier').select('tier_title').where({id : row.pricing_tier})
.then(tier_title =>{
row.tier_title = tier_title[0].tier_title;
return row;
})
});
})).then(response => {
cb(sendData);
});
Hear it two query in promise 'designer.settings' and 'designer.pricing_tier'.
when execute 'designer.settings' i got that result in row after execute 'designer.pricing_tier' but that output not get in row. row.tier_title = tier_title[0].tier_title not in final sendData.
How sync both query in one promise?
Not sure if the query actually does exact same thing, but this merely demonstrates the basic idea how to do the above query correctly with knex.
Effectively the same thing with joining the pricing_tier to prevent need for 2 separate queries.
Promise.all(
sendData.franchisee.map(row => {
return knex('pricing_tier')
.withSchema('designer') // <-- selecting schema correctly in knex
// this join could have been done as a subquery in select too...
.join('settings', 'settings.setting_key', knex.raw('?', ['PRICING_TIER']))
.select('settings.value', 'pricing_tier.tier_title')
.where('pricing_tier.id', row.pricing_tier)
.then(rows => {
row.pricing_tier = rows[0].value;
row.tier_title = rows[0].tier_title;
return row;
});
})
).then(response => {
cb(sendData); // <--- generally bad idea to mix promises and callbacks
});
Resulting SQL is like this:
select
`settings`.`value`,
`pricing_tier`.`tier_title`
from `designer`.`pricing_tier`
inner join `designer`.`settings` on `settings`.`setting_key` = 'PRICING_TIER'
where `pricing_tier`.`id` = 3219
You should wrap both queries into a promise which resolves only when both query have finished the job like this:
Promise.all(sendData.franchisee.map(row => {
return new Promise((resolve) => {
knex('designer.settings').select('value').where({setting_key : 'PRICING_TIER'})
.then(pricing_tier => {
row.pricing_tier = pricing_tier[0].value;
knex('designer.pricing_tier').select('tier_title').where({id : row.pricing_tier})
.then(tier_title =>{
row.tier_title = tier_title[0].tier_title;
resolve(row);
})
});
});
})).then(response => {
cb(sendData);
});
I have got a scenario where I would want the below query executed using sequelize.
select * from master where catg_level = 1 and obj_id in (select obj_id from master where catg_level = 2) order by position;
I've the below code written in sequelize.
Master.all({
where: {catg_level: '1'},
order: 'position ASC',
include: [{
model: Master,
as: 'sub-menu',
where: {catg_level: '2'}
}]
})
.then(function(a){
try {
console.log(JSON.stringify(a));
} catch (e) {
console.log(e);
}
});
The SQL generated this
The condition catg_level = 2 is added to the main query instead of being added as a subquery. I understand this is the actual functioning. But is there a workaround to get this done? Please advise.
Thanks in advance.
You can use sequelize.literal:
{
where: {
catg_level: '1',
obj_id:{
in:[sequelize.literal('(select obj_id from master where catg_level = 2)')]
}
},
order: 'position ASC',
}