Sequelize attribute with alias seems undefined - mysql

I'm trying to get id of AttributeValue model with an alias of attribute_value_id as below but attribute_value_id seems undefined in otherOptions constant.
const otherOptions = await AttributeValue.findAll({
where: {
id: {
[Op.in]: attributeValueIds
} },
attributes: [
['id', 'attribute_value_id'],
'attribute_id',
'value'
]
})
I'm fallowing sequlize documantation about querying and the below query is built by sequelize but there is no alias attribute in the resulting object.
SELECT `id` AS `attribute_value_id`, `attribute_id`, `value` FROM `attribute_values` AS `attribute_value` WHERE `attribute_value`.`id` IN (1, 1, 1, 1, 19);

You can get it with otherOptions[0].getDataValue('attribute_value_id')

Related

how to group data entries with same id into a single entry?

I am a beginner in MySQL as well as Typeorm. So my query returns data with the same ID like:
[
{
id: "1",
name: "john",
place: "San Francisco"
},
{
id: "1",
name: "john",
place: "Mumbai"
}
]
Now I want data where there is an entry with a unique id, let's say:
[
{
id: "1",
name: "john",
place: ["San Francisco", "Mumbai"]
}
]
can someone help me, how do I groupBy to achieve this result?
I doubt that you can get an array, but you could use group_concat.
https://mariadb.com/kb/en/group_concat/
The query would be something like
SELECT `id`, group_concat(`name`), group_concat(`place`) FROM <table_name> GROUP BY `id`
if the name doesn't need to be concatenated
SELECT `id`, `name`, group_concat(`place`) FROM <table_name> GROUP BY `id`
And then in your code you can split that string in array. Either use ',' which I think it's the default separator or use a custom one like '!#$!'
With MySQL you can use GROUP_CONCAT:
SELECT
id, name, GROUP_CONCAT(place)
FROM
<table_name>
GROUP BY
id
With TypeScript you can use Array.prototype.reduce():
const data = [{id: "1",name: "john",place: "San Francisco"},{id: "1",name: "john",place: "Mumbai"}]
const dataHash = data.reduce((a, { id, name, place }) => {
a[id] = a[id] || { id, name, place: [] }
a[id].place.push(place)
return a
}, {})
const result = Object.values(dataHash)
console.log(result)

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},
]
})
}

how to serialize using entityframework ICollection 'my way'

i have
table of users. - key IdUser , and other colsumns...
table of perms key IdPerm, and column PermName
and table of UserPerms key IdUserPermand columns IdPerm IdUser and Value
so when i select this user using Entity Framework and return it as json from api i get
{ IdUser : 1, login: "xx", name: "xxx",
UserPerms : [
{IdUserPerm : 1, IdUser : 1, idPerm: 1, value: 1, idPermNavigation: {idperm: 1, PermName:"Feature1"}}
{IdUserPerm : 2, IdUser : 1, idPerm: 2, value: 2, idPermNavigation: {idperm: 2, PermName:"Feature2"}}
{IdUserPerm : 3, IdUser : 1, idPerm: 3, value: 5, idPermNavigation: {idperm: 3, PermName:"Feature3"}}
]
}
is there any way i can configure this json serializer or .net core EF so i get result
UserPerms :{permname:value, next..}
so in this example to get
{IdUser:1, login:"xx", name:"yy",..., UserPerms:{Feature1:1, Feature2:2, Feature3:5}}
or any way to redesign DB so EF got this as 'default' ?
thanks and regards !
You can workaround by create DTO like
class UserPermResult {
int IdUser;
string Login;
...
ICollection<Perm> UserPerms;
}
class Perm {
string Name;
int Value;
}
and use Select linQ
values.Select(f=> new UserPermResult {
IdUser = f.IdUser,
...
UserPerms = f.UserPerms.Select(p=> new Perm{
Name = p.IdPermNavigation?.PermName,
Value = p.Value
})
});

Sequelize (or clear SQL) query for selecting rows what includes value in JSON field?

I have rows in my MYSQL and I Need Sequelize.js query.
Every row have col of type JSON what include this for example:
[
{id: 1234, blah: "test"},
{id: 3210, blah: "test"},
{id: 5897, blah: "test"}
]
I have id and I need to select row what include this id in at least one object in array.
Raw mysql query will be like this:
SELECT * FROM `user` WHERE JSON_CONTAINS(`comments`, '{"id": 1234}');
Simple sequelize example:
const { fn, col, cast } = this.sequelize;
const User = this.sequelize.define('user', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
comments: DataTypes.JSON,
defaultValue: [],
})
User.findAll({
where: fn('JSON_CONTAINS', col('comments'), cast('{"id": 1234}', 'CHAR CHARACTER SET utf8')),
})
.then(users => console.log('result', users.map(u => u.get())))
.catch(err => console.log('error', err));
Cast function is used to unescape double quotes around "id" to avoid wrong query string like this:
SELECT * FROM `user` WHERE JSON_CONTAINS(`comments`, '{\"id\": 1234}');
There is one more dirty mysql query example (don't use it):
SELECT * FROM `user` WHERE `comments` LIKE '%"id": 1234%';

How to return nested JSON in node js

I have three different tables.
1. Order details (id, itemId,date,userId)
2. Item details (id, itemName, quantity)
3. User details (id, userName)
I want to return a JSON as:
{[
{
orderId = 1,
items = [
{
itemId = 1,
itemName = ITEM_DEMO,
},
{
itemId = 2,
itemName = ITEM_DEMO2,
}
],
userDetails = {
userId = 1,
userName = TEST_USER
}
}
]}
How can we do this in Node JS. Im using MySQL.
First of all you should read about object and json in javascript.
For parsing your data from mySql to json do the following steps:
Create an object that is filled with your data from mySql.
const ArrayObjectFilledWithMysqlData = [
{
orderId: 1,
items: [{
itemId: 1,
itemName: ITEM_DEMO,
},
{
itemId: 2,
itemName: ITEM_DEMO2,
}]
},
{
userDetails: {
userId: 1,
userName: TEST_USER
}
}
]
Parse the Array to json.
const jsonFromData = JSON.stringify(ArrayObjectFilledWithMysqlData)