Why use association in sequelize orm? - node.js

I made some api system with nodejs.
Also I use sequelize(version 4) for communicates with MySQL.
Below is my model structure.
[user]
no(PK)
userid
userpw
[article]
no(PK)
subject
content
writer(FK to user's userid)
I made with sequelize orm define like this.
import Sequelize from 'sequelize';
const sequelize = new Sequelize('db', 'user', 'pw', {
host: '127.0.0.1',
dialect: 'mysql'
})
const User = sequelize.define('user', {
no: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
userid: {
type: Sequelize.STRING(30),
allowNull: false,
unique: true
},
userpw: {
type: Sequelize.STRING(30),
allowNull: false
}
}, {
freezeTableName: true,
timestamps: true,
underscored: true
});
const Article = sequelize.define('article', {
no: {
type: Sequelize.INTEGER,
primaryKey: true
},
subject: {
type: Sequelize.STRING(50),
allowNull: false
},
content: {
type: Sequelize.STRING(100),
allowNull: false
},
writer: {
type: Sequelize.STRING(30),
references: {
model: 'user',
key: 'userid'
}
}
}, {
freezeTableName: true,
timestamps: true,
underscored: true
})
sequelize.sync({
force: true
});
export default { User, Article };
In Article model, I define write and refer to User's userid.
So Article's writer column is Foreign Key refer to User's userid.
Because If user was deleted, related article have to delete.
Run that code, table will be created and structure is like this.
mysql> desc user;
+------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+----------------+
| no | int(11) | NO | PRI | NULL | auto_increment |
| userid | varchar(30) | NO | UNI | NULL | |
| userpw | varchar(30) | NO | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+------------+-------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)
mysql> desc article;
+------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| no | int(11) | NO | PRI | NULL | |
| subject | varchar(50) | NO | | NULL | |
| content | varchar(100) | NO | | NULL | |
| writer | varchar(30) | YES | MUL | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+------------+--------------+------+-----+---------+-------+
6 rows in set (0.00 sec)
After do that, I searched more information about association in sequelize orm.
And I found that sequelize has many association like hasMany, BelongsTo, 'hasMany`, ...
So I add User.hasMany(Article); to my previous code and run it, it add more columns.
mysql> desc article;
+------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| no | int(11) | NO | PRI | NULL | |
| subject | varchar(50) | NO | | NULL | |
| content | varchar(100) | NO | | NULL | |
| writer | varchar(30) | YES | MUL | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
| user_no | int(11) | YES | MUL | NULL | |
+------------+--------------+------+-----+---------+-------+
7 rows in set (0.00 sec)
user_no column was added.
I think it automatically added by hasMany function.
But in my case, I do not have to create user_no, Because I already refer to User's user_id column.
Overall, my question is:
I think I do not have to set hasMany in my case. Is it right?
Why ORM offer assocation function? Just for convenience? or Is there any reason for it?
Thanks.

Related

Swapping rows for a column that has unique constraint

I'm using postgresql and sequelize to do my db operations
Suppose I have a person table like this:
id (pkey) | name | email (unique) | company
1 | john | john#x.com | abc
2 | mary | mary#y.com | abc
3 | will | NULL | xyz
I make the unique constraint like this:
const PersonData = sequelize.define(
'users',
{
....
email: {
type: Sequelize.STRING,
allowNull: false,
unique: {
args: true,
msg: 'Email already in use!',
},
},
....
},
I'm getting payload like
{{
id: 1,
email: mary#y.com
},
{
id: 2,
email: john#x.com
}}
I want to swap the emails for id 1 and id 2 here. How can I do that using sequelize?
The output I want:
id (pkey) | name | email (unique) | company
1 | john | mary#y.com | abc
2 | mary | john#x.com | abc
3 | will | NULL | xyz

ErrorException Undefined array key 7 on Laravel Excel when import or upload excel file

I just doing project import excel using laravel.
But there is an error when import / upload file excel and for web page can open and work.
ErrorException
Undefined array key 7
public function model(array $row)
{
return new Dso([
'id_dso' => $row[1],
'id_rso' => $row[2],
'id_focus' => $row[3],
'id_wilayah' => $row[4],
'id_grup_wilayah' => $row[5],
'nama_dso' => $row[6],
'status' => $row[7],
]);
}
and my table on database format is
+-----------------+---------------------+------+-----+---------------------+-------------------------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+---------------------+------+-----+---------------------+-------------------------------+
| id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| id_dso | bigint(20) unsigned | NO | | NULL | |
| id_rso | bigint(20) unsigned | NO | | NULL | |
| id_focus | bigint(20) unsigned | NO | | NULL | |
| id_wilayah | bigint(20) unsigned | NO | | NULL | |
| id_grup_wilayah | bigint(20) unsigned | NO | | NULL | |
| nama_dso | varchar(255) | NO | | NULL | |
| created_by | varchar(255) | NO | | NULL | |
| created_date | timestamp | NO | | current_timestamp() | on update current_timestamp() |
| modified_by | varchar(255) | NO | | NULL | |
| modified_date | timestamp | YES | | NULL | |
| status | tinyint(1) | NO | | NULL | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
+-----------------+---------------------+------+-----+---------------------+-------------------------------+
14 rows in set (0.009 sec)
and my data sample is
Import data Sample
I'm using laravel 8.6 and my datbase is MariaDb.
Please start your array $row index from $row[0] instead of $row[1] as given as under
public function model(array $row)
{
return new Dso([
'id_dso' => $row[0],
'id_rso' => $row[1],
'id_focus' => $row[2],
'id_wilayah' => $row[3],
'id_grup_wilayah' => $row[4],
'nama_dso' => $row[5],
'status' => $row[6],
]);
}
Try this.
Array starts with index 0.
So start from $row[0] until $row[6]
The key status will be $row[6] in your case.
public function model(array $row)
{
return new Dso([
'id_dso' => $row[0],
'id_rso' => $row[1],
'id_focus' => $row[2],
'id_wilayah' => $row[3],
'id_grup_wilayah' => $row[4],
'nama_dso' => $row[5],
'status' => $row[6],
]);
}
try this
public function model(array $row)
{
return new Dso([
'id_dso' => $row[1],
'id_rso' => $row[2],
'id_focus' => $row[3],
'id_wilayah' => $row[4],
'id_grup_wilayah' => $row[5],
'nama_dso' => $row[6],
'status' => ($row[7]) ? $row[7] : ' ',
]);
}

nodejs Dynamo DB document client. How to write filter expression for an attribute that exists with null data type

I have an attribute with null value. and some rows have boolean value. Now I want to write a filter expression to filter for the rows with attribute having null value. I am using dynamodb document client.
If you look at the docs, for a scan you can do:
ScanFilter: {
'<AttributeName>': {
ComparisonOperator: EQ | NE | IN | LE | LT | GE | GT | BETWEEN | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH, /* required */
AttributeValueList: [
someValue /* "str" | 10 | true | false | null | [1, "a"] | {a: "b"} */,
/* more items */
]
},
/* '<AttributeName>': ... */
}
If you are using query:
QueryFilter: {
'<AttributeName>': {
ComparisonOperator: EQ | NE | IN | LE | LT | GE | GT | BETWEEN | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH, /* required */
AttributeValueList: [
someValue /* "str" | 10 | true | false | null | [1, "a"] | {a: "b"} */,
/* more items */
]
},
/* '<AttributeName>': ... */
},
They both clearly support filtering by attributes with value null.

nodejs - mongodb $lte and $gte not working with $lookup

I need to get record by price range but the query is working fine in shell but not in nodejs. Here is query:
db.model.aggregate([
{ $match: { make_id: make_id } },
{
$lookup: {
from: 'variants',
localField: '_id',
foreignField: 'model_id',
as: 'variant_list'
}
},
{
$unwind: {
path: '$variant_list',
preserveNullAndEmptyArrays: false
}
},
{$match: {status:1, $and:[{'variant_list.price': {$lte:Number(max_price)}}]}},
{$project: { make_id: 1, model_name: 1, variant_list: '$variant_list'}}
])
I have checked the price in database. it is stored like NumberInt(300000) and in my query i have parsed in integer type like => max_price to Number(max_price).
and it gives me all record which are less than and equal to 300000 but it also gives the record which are less than 400000.
But If i'm not using aggregate framework then it is giving me perfect result:
db.model.find({status:1, $and:[{'variant_list.price': {$lte:Number(max_price)}}]})
I dont know why $lte not working perfectly with aggregate and $lookup.
Please Help!!
Updated Sample Collection and Documents
MakeId = a123;
Models:
-----------------------------
mid | makeid | model |
-----------------------------
m1 | a123 | MDLi1 |
m2 | a123 | MDLi2 |
m3 | a123 | MDLi3 |
m4 | a123 | MDLi4 |
m5 | a123 | MDLi5 |
-----------------------------
Variants:
----------------------------------------
vid | modelid | variants | price |
----------------------------------------
v1 | m1 | VARi1 | 150000 |
v2 | m1 | VARi2 | 250000 |
v3 | m1 | VARi3 | 300000 |
v4 | m1 | VARi4 | 350000 |
v5 | m1 | VARi5 | 380000 |
v6 | m2 | VARi6 | 250000 |
v7 | m2 | VARi7 | 280000 |
v8 | m2 | VARi8 | 380000 |
v9 | m2 | VARi9 | 400000 |
v10 | m2 | VARi10 | 450000 |
----------------------------------------
I need to get model detail and variants list by variant price like price range should be between 0 to 300000
My Desire result is :
{
"data": [
{
"makeid": "a123",
"modelid": "m1",
"variant_list": [
{
"variant_id": "v1",
"variant_name": "VARi1",
"price": 150000
},
{
"variant_id": "v2",
"variant_name": "VARi2",
"price": 250000
},
{
"variant_id": "v3",
"variant_name": "VARi3",
"price": 300000
}
]
},
{
"makeid": "a123",
"modelid": "m2",
"variant_list": [
{
"variant_id": "v6",
"variant_name": "VARi6",
"price": 250000
},
{
"variant_id": "v7",
"variant_name": "VARi7",
"price": 280000
}
]
}
]
}

Sails.js One to many association

Using the example given on the Sails.js documentation page, I get the following error : "Maximum call stack size exceeded error".
items.find().populate("user", {name:givenName}).exec(function(err, response) {
console.log(response);
}
The matter is that when I look with wireshark, the query on the database tries to find every user (and the database is big), but it doesn't make any join.
items
+-----------+--------------+------+-----+
| Field | Type | Null | Key |
+-----------+--------------+------+-----+
| id | int(6) | NO | PRI |
| name | varchar(255) | NO | |
+-----------+--------------+------+-----+
user
+-----------+--------------+------+-----+
| Field | Type | Null | Key |
+-----------+--------------+------+-----+
| id | int(6) | NO | PRI |
| name | varchar(255) | NO | |
| item_id | int(11) | YES | MUL |
+-----------+--------------+------+-----+
Should be as simple as:
items
.find()
.populate("user")
.where({name: givenName}) //or .where({user: {name: givenName}})
.exec(function(err, response) {
console.log(response);
});
Ok, If like you said you want only items for a specific user do this :
user.findOneByName(givenName).exec(function(err, user) {
items.find().where({user : user.id}).exec(function(err, response) {
console.log(response);
});
});

Resources