Sequelize populate joined table attributes - mysql

I have a few tables and I want to do some includes on a joined table, but I can't seem to figure it out. Here are my models:
/* Staff model */
const model = {
fisrName: {
type: DataTypes.INTEGER,
references: { model: 'Roles', key: 'id' },
},
lastName: {
type: DataTypes.INTEGER,
references: { model: 'Profiles', key: 'id' },
}
};
const Staff = createModel('Staff', model, { paranoid: true });
export default Staff
/* Service model */
const model = {
name: {
type: DataTypes.STRING,
},
category: {
type: DataTypes.STRING,
},
description: {
type: DataTypes.STRING,
}
};
const Service = createModel('Service', model, {});
export default Service;
/* Appointment model */
const model = {
endDate: {
type: DataTypes.DATE,
},
startDate: {
type: DataTypes.DATE,
},
day: {
type: DataTypes.DATE,
},
};
const Appointment = createModel('Appointment', model, {})
Appointment.belongsToMany(Service, { through: 'Products', as: 'products' });
export default Appointment;
/* Products model */
const model = {
serviceId: {
type: DataTypes.INTEGER,
},
appointmentId: {
type: DataTypes.INTEGER,
},
staffId: {
type: DataTypes.INTEGER,
references: { model: 'Staff', key: 'id' },
}
};
const Product = createModel('Product', model, {});
Product.belongsTo(Staff, { foreignKey: 'staffId', as: 'staff' });
export default Product;
This is my appointment query, where I include the services array, and on this services array, I have a Products object, and in this object I have a staffId that I want to populate, and I'm not sure how. I have tried different ways, but nothing worked.
const appointment = await Appointment.findByPk(req.params.id, {
include: [
{
model: Service,
as: 'services',
through: { attributes: { include: ['id', 'staffId', 'serviceId', 'appointmentId'], exclude: ['createdAt', 'updatedAt', 'AppointmentId', 'ServiceId'] },
},
],
});
And this is my response:
{
"startDate": "date",
"endDate": "date",
"day": "date",
"services": [{
"id": 1,
"name": "Service name",
"category": "service category",
"description": "service description",
"Products": {
"id": 1,
"staffId": 2,
"serviceId": 1,
"appointmentId": 1
}
}]
}
What I want is to do is to populate the staffId from Products with the model from the collection, something like this:
{
"startDate": "date",
"endDate": "date",
"day": "date",
"services": [{
"id": 1,
"name": "Service name",
"category": "service category",
"description": "service description",
"Products": {
"id": 1,
"staffId": {
"firstName": "First Name",
"lastName": "Last Name"
},
"serviceId": 1,
"appointmentId": 1
}
}]
}

const appointment = await Appointment.findByPk(req.params.id, {
include: [
{
model: Service,
as: 'services',
through: {
attributes: { include: ['id', 'staffId', 'serviceId', 'appointmentId'], exclude: ['createdAt', 'updatedAt', 'AppointmentId', 'ServiceId'] },
},
include: [{
as: 'Products', model: Product,
include: 'staff'
}]
}
]
});

Related

ExtJS model associations with jsonapi specification

We are creating a new version our API (v2) adopting the JSON:API specification (https://jsonapi.org/). I'm not being able to port the ExtJS model associations (belongs_to) to the new pattern.
The ExtJS documentation only shows how to use a nested relation in the same root node (https://docs.sencha.com/extjs/4.2.2/#!/api/Ext.data.association.Association).
v1 data (sample):
{
"data": [
{
"id": 1,
"description": "Software Development",
"area_id": 1,
"area": {
"id": 1,
"code": "01",
"description": "Headquarters"
}
},
],
"meta": {
"success": true,
"count": 1
}
}
v2 data (sample):
{
"data": [
{
"id": "1",
"type": "maint_service_nature",
"attributes": {
"id": 1,
"description": "Software Development",
"area_id": 1
},
"relationships": {
"area": {
"data": {
"id": "1",
"type": "area"
}
}
}
}
],
"included": [
{
"id": "1",
"type": "area",
"attributes": {
"id": 1,
"code": "01",
"description": "Headquarters"
}
}
],
"meta": {
"success": true,
"count": 1
}
}
My model:
Ext.define('Suite.model.MaintServiceNature', {
extend: 'Ext.data.Model',
fields: [
{ desc: "Id", name: 'id', type: 'int', useNull: true },
{ desc: "Area", name: 'area_id', type: 'int', useNull: true },
{ desc: "Description", name: 'description', type: 'string', useNull: true, tableIdentification: true }
],
associations: [
{
type: 'belongsTo',
model: 'Suite.model.Area',
foreignKey: 'area_id',
associationKey: 'area',
instanceName: 'Area',
getterName: 'getArea',
setterName: 'setArea',
reader: {
type: 'json',
root: false
}
}
],
proxy: {
type: 'rest',
url: App.getConf('restBaseUrlV2') + '/maint_service_natures',
reader: {
type: 'json',
root: 'data',
record: 'attributes',
totalProperty: 'meta.count',
successProperty: 'meta.success',
messageProperty: 'meta.errors'
}
}
});
Any ideias on how to setup the association to work with the v2 data?
I'm honestly taking a stab at this one... I haven't used Ext JS 4 in years, and I wouldn't structure my JSON like JSON:API does, but I think the only way you can accomplish this is by rolling your own reader class. Given that you have generic properties for your data structure, this reader should work for all scenarios... although, I'm not too familiar with JSON:API, so I could be totally wrong. Either way, this is what I've come up with.
Ext.application({
name: 'Fiddle',
launch: function () {
Ext.define('MyReader', {
extend: 'Ext.data.reader.Json',
alias: 'reader.myReader',
root: 'data',
totalProperty: 'meta.count',
successProperty: 'meta.success',
messageProperty: 'meta.errors',
/**
* #override
*/
extractData: function (root) {
var me = this,
ModelClass = me.model,
length = root.length,
records = new Array(length),
dataConverter,
convertedValues, node, record, i;
for (i = 0; i < length; i++) {
node = root[i];
var attrs = node.attributes;
if (node.isModel) {
// If we're given a model instance in the data, just push it on
// without doing any conversion
records[i] = node;
} else {
// Create a record with an empty data object.
// Populate that data object by extracting and converting field values from raw data.
// Must pass the ID to use because we pass no data for the constructor to pluck an ID from
records[i] = record = new ModelClass(undefined, me.getId(attrs), attrs, convertedValues = {});
// If the server did not include an id in the response data, the Model constructor will mark the record as phantom.
// We need to set phantom to false here because records created from a server response using a reader by definition are not phantom records.
record.phantom = false;
// Use generated function to extract all fields at once
me.convertRecordData(convertedValues, attrs, record, me.applyDefaults);
if (me.implicitIncludes && record.associations.length) {
me.readAssociated(record, node);
}
}
}
return records;
}
});
Ext.define('Suite.model.Area', {
extend: 'Ext.data.Model',
fields: [{
name: 'type',
type: 'string'
}]
});
Ext.define('Suite.model.MaintServiceNature', {
extend: 'Ext.data.Model',
fields: [{
desc: "Id",
name: 'id',
type: 'int',
useNull: true
}, {
desc: "Area",
name: 'area_id',
type: 'int',
useNull: true
}, {
desc: "Description",
name: 'description',
type: 'string',
useNull: true,
tableIdentification: true
}],
associations: [{
type: 'belongsTo',
model: 'Suite.model.Area',
associatedName: 'Area',
foreignKey: 'area_id',
associationKey: 'relationships.area.data',
instanceName: 'Area',
getterName: 'getArea',
setterName: 'setArea'
}],
proxy: {
type: 'rest',
url: 'data1.json',
reader: {
type: 'myReader'
}
}
});
Suite.model.MaintServiceNature.load(null, {
callback: function (record) {
console.log(record.getData(true));
}
});
}
});

One to many relationship in sequelize with MYSQL

I have two tables:
const attr = {
name: {
type: DataTypes.STRING,
},
};
const Tags = createModel('Tags', attr, {});
and:
const attr = {
tagId: {
type: DataTypes.INTEGER,
references: { model: 'Tags', key: 'id' },
}
}
const Client = createModel('Client', attr, {})
Client.belongsTo(Tag, { foreignKey: 'tagId', as: 'tags' });
and my query is this:
const clientCount = await Client.findAll({
include: [ { model: Tags, as: 'tags' } ],
attributes: { exclude: 'tagId' }
});
and this is my response:
{
"id": 1,
"createdAt": "2020-01-20T00:00:00.000Z",
"updatedAt": "2020-01-22T00:00:00.000Z",
"tags": {
"id": 1,
"name": "New tag",
"createdAt": "2020-01-20T00:00:00.000Z",
"updatedAt": "2020-01-20T00:00:00.000Z"
}
}
but I want my tags to be an array, so I guest I have to define a one to many association, but everything I tried so far failed.
What I want is tags to be an array, where I can add multiple tag objects:
{
"id": 1,
"createdAt": "2020-01-20T00:00:00.000Z",
"updatedAt": "2020-01-22T00:00:00.000Z",
"tags": [
{
"id": 1,
"name": "New tag",
"createdAt": "2020-01-20T00:00:00.000Z",
"updatedAt": "2020-01-20T00:00:00.000Z"
}
]
}
Method1
We need new model as Client_Tag
const attr = {
clientId: {
type: DataTypes.INTEGER,
},
tagId: {
type: DataTypes.INTEGER,
},
};
const Client_Tag = createModel('Client_Tag', attr, {});
Client.belongsToMany(Tag, {
foreignKey: 'clientId',
otherKey: 'tagId',
through: models.Client_Tag,
as: 'tags'
});
const clientCount = await Client.findAll({
include: [ { model: Tags, as: 'tags' } ],
attributes: { exclude: 'tagId' }
});
Method2
const attr = {
name: {
type: DataTypes.STRING,
},
clientId: { // need clientId in tag model, and remove 'tagId' from client model
type: DataTypes.INTEGER,
}
};
const Tags = createModel('Tags', attr, {});
Client.belongsToMany(Tag, { foreignKey: 'tagId', as: 'tags' });

Extjs load combo boxes dynamically using recursive json data

I have set of models and a store as given below.
Ext.define('User', {
extend: 'Ext.data.Model',
fields: [
'id', 'name', 'total'],
hasMany: {
model: 'Order',
name: 'orders'
},
proxy: {
type: 'rest',
url: 'users.json',
reader: {
type: 'json',
root: 'users'
}
}
});
Ext.define('Order', {
extend: 'Ext.data.Model',
fields: [
'id', 'total'],
hasMany: {
model: 'OrderItem',
name: 'orderItems',
associationKey: 'order_items'
},
belongsTo: 'User'
});
Ext.define('OrderItem', {
extend: 'Ext.data.Model',
fields: [
'id', 'price', 'quantity', 'order_id', 'product_id'],
belongsTo: ['Order', {model: 'Product', associationKey: 'product'}]
});
var store = Ext.create('Ext.data.Store', {
model: 'User'
});
And below is the json file which I use to load data.
{
"users": [
{
"id": "123",
"name": "Ed",
"orders": [
{
"id": "50",
"total": "100",
"order_items": [
{
"id" : "20",
"price" : "40",
"quantity": "2",
"product" : {
"id": "1000",
"name": "MacBook Pro"
}
},
{
"id" : "21",
"price" : "20",
"quantity": "3",
"product" : {
"id": "1001",
"name": "iPhone"
}
}
]
}
]
},
{
"id": "124",
"name": "Nisha",
"orders": [
{
"id": "52",
"total": "1004",
"order_items": [
{
"id" : "22",
"price" : "40",
"quantity": "23",
"product" : {
"id": "1002",
"name": "Nokia"
}
},
{
"id" : "23",
"price" : "100",
"quantity": "3",
"product" : {
"id": "1003",
"name": "apple"
}
}
]
}
]
}
]
}
I am loading the user IDs to L1_combo_box as below and according to the user ID the user selects from the L1_combo_box, I need to load order_item ids to L2_combo_box .
For example, I load user ids 123, 124 to L1_combo_box and when user selects 123 from L1 combo box, I need to load 20,21 to L2 combo box. If user selects 124, then I need to load 22,23.
Below is the partially completed code. can anyone help me to complete this?
var searchFormFieldsetItems = [
{
xtype: 'fieldcontainer',
combineErrors: true,
name: 'search_form_fieldset_items',
msgTarget: 'side',
fieldLabel: '',
defaults: {
hideLabel: true
},
items: [{
xtype: 'combo',
name: 'L1_combo_box',
displayField: 'id',
valueField: 'id',
queryMode: 'remote',
store:store,
listeners: {
change: {
fn: function(combo, value) {
var store1 = 'users/orders/order_items/';//This line is partially completed
L2_combo_box.bindStore(store1);
}
}
}
},{
xtype: 'combo',
name: 'L2_combo_box',
displayField: 'id',
valueField: 'id'
}
]
}
];
For this you need to use select for combobox and inside of select event you need to use loadData() method of store to adding data in second combo.
In this FIDDLE, I have created a demo using your code and put my efforts for showing data in second combo. I hope this will help/guide you to achieve your requirement.
CODE SNIPPET
Ext.application({
name: 'Fiddle',
launch: function () {
Ext.define('User', {
extend: 'Ext.data.Store',
autoLoad: true,
alias: 'store.user',
fields: ["id", "name", "orders"],
proxy: {
type: 'ajax',
url: 'users.json',
reader: {
type: 'json',
rootProperty: 'users'
}
}
});
Ext.define('Order', {
extend: 'Ext.data.Store',
alias: 'store.order',
field: ["id", "price", "quantity", "product"],
storeId: 'order'
});
Ext.create('Ext.form.Panel', {
title: 'Example Combo',
bodyPadding: 5,
defaults: {
width: 250
},
// The fields
defaultType: 'combo',
items: [{
name: 'L1_combo_box',
displayField: 'id',
valueField: 'id',
queryMode: 'local',
emptyText: 'Select user',
store: {
type: 'user'
},
listeners: {
select: function (combo, rec) {
var L2_combo_box = combo.up('form').getForm().findField('L2_combo_box'),
order = rec.get('orders') || [],
data = [];
//reset combo value
L2_combo_box.reset();
//If order have multipe data then need use forEach for all data
order.forEach(item => {
data = data.concat(item.order_items);
});
//load data in combo store
Ext.getStore('order').loadData(data);
}
}
}, {
emptyText: 'Select order items',
name: 'L2_combo_box',
displayField: 'id',
valueField: 'id',
queryMode: 'local',
store: {
type: 'order'
}
}],
renderTo: Ext.getBody()
});
}
});

Sequelize set alias attributes name after join

After a join operation among three models I received a valid result but I would rename the attributes generated by the join operation of the findAll
Query:
const orchards = await db.Area.findAll({
include: [db.AreaCoordinate, db.Crop],
attributes: ['id', 'name']
});
AreaCoordinate Model:
module.exports = function (sequelize, DataTypes) {
var AreaCoordinate = sequelize.define('AreaCoordinate', {
latitude: {
type: DataTypes.STRING(45),
allowNull: true
},
longitude: {
type: DataTypes.STRING(45),
allowNull: true
}
}, {
classMethods: {
associate: function (models) {
AreaCoordinate.belongsTo(models.Area, {foreignKey: 'areaId'});
}
}
});
return AreaCoordinate;
};
Crop Model:
module.exports = function (sequelize, DataTypes) {
var Crop = sequelize.define('Crop', {
name: {
type: DataTypes.STRING(45),
allowNull: true
},
lang: {
type: DataTypes.STRING(45),
allowNull: true
}
}, {
classMethods: {
associate: function (models) {
Crop.hasMany(models.Area, {foreignKey:'cropId'})
}
}
});
return Crop;
};
Area Model:
module.exports = function (sequelize, DataTypes) {
var Area = sequelize.define('Area', {
name: DataTypes.STRING
}, {
classMethods: {
associate: function (models) {
// example on how to add relations
Area.belongsTo(models.Crop, {foreignKey: 'cropId'});
Area.belongsTo(models.Orchard, {as: 'orchard'});
Area.hasMany(models.AreaCoordinate, {foreignKey:'areaId'})
}
}
});
return Area;
};
I would receive from the query a JSON like this:
{
"status": 200,
"status_message": "OK",
"data": {
"orchard": [
{
"name": "pantano",
"coordinates": [
{
"id": 115,
"latitude": "1",
"longitude": "2",
"createdAt": "2017-08-29T12:03:11.000Z",
"updatedAt": "2017-08-29T12:03:11.000Z",
"areaId": 28
},
{
"id": 116,
"latitude": "1",
"longitude": "2",
"createdAt": "2017-08-29T12:03:11.000Z",
"updatedAt": "2017-08-29T12:03:11.000Z",
"areaId": 28
}
],
"cropId": 10
}
]
}
}
But what I receive is (look AreaCoordinates and Crop):
{
"status": 200,
"status_message": "OK",
"data": {
"orchard": [
{
"name": "pantano",
"AreaCoordinates": [
{
"id": 115,
"latitude": "1",
"longitude": "2",
"createdAt": "2017-08-29T12:03:11.000Z",
"updatedAt": "2017-08-29T12:03:11.000Z",
"areaId": 28
},
{
"id": 116,
"latitude": "1",
"longitude": "2",
"createdAt": "2017-08-29T12:03:11.000Z",
"updatedAt": "2017-08-29T12:03:11.000Z",
"areaId": 28
}
],
"Crop": 10
}
]
}
}
I tried to set some alias for AreaCoordinates and Crop but I couldn't find a solution. Thank you in advance for your support.
Write query like this:
const result = await Table.findAll({
attributes: ['id', ['foo', 'bar']] //id, foo AS bar
});
By default in Sequelize association, it will set the attribute name as the related model name. For your case, the related model named AreaCoordinates, so the attribute name in return will be AreaCoordinates. You should use as. Modify yours and Try this:
###findAll Query:
const orchards = await db.Area.findAll({
include: [
{
model: db.AreaCoordinate,
as: 'coordinates'
}, {
model: db.Crop,
as: 'cropId',
attributes: ['id']
}],
attributes: ['id', 'name']
});
###Area Model
module.exports = function (sequelize, DataTypes) {
var Area = sequelize.define('Area', {
name: DataTypes.STRING
}, {
classMethods: {
associate: function (models) {
// example on how to add relations
Area.belongsTo(models.Crop, {
foreignKey: 'cropId',
as: 'cropId'
});
Area.belongsTo(models.Orchard, {as: 'orchard'});
Area.hasMany(models.AreaCoordinate, {
foreignKey:'areaId',
as: 'coordinates'
})
}
}
});
return Area;
};

Sequelize findAll with association and foreign key

I'm using sequelize to model a mySql-database schema in my node-application. Let's say I have 3 table: Project, User and Role.
It's a "Many to Many" association between Project and User through "Project_User" where is defined the role of a user for a project.
Project Model :
var Project = sequelize.define('Project', {
name:{type: DataTypes.STRING, unique: true}
},
classMethods: {
associate: function(models) {
Project.belongsToMany(models.User, { through: 'Project_User', as: 'users'});
}
}
// Methods...
);
User Model :
var User= sequelize.define('User', {
name:{type: DataTypes.STRING, unique: true}
},
classMethods: {
associate: function(models) {
User.belongsToMany(models.Project, { through: 'Project_User', as: 'projects'});
}
}
// Methods...
);
And here is the association table Project_User Model :
var Project_User = sequelize.define('Project_User', {
role:
{
type: DataTypes.INTEGER,
allowNull: false,
references: 'Role',
referencesKey: 'id'
}
},{
classMethods: {
associate: function(models) {
Project_User.belongsTo(models.Role, {foreignKey: 'role'});
}
}
});
Now, I want to find all project, with their users and their role. So I've used findAll with the "include" parameters like below:
models.Projects.findAll({
include:[
{
model: models.User,
as:'users',
through: {attributes: ['role'], as: 'role'}
}]
}).then(function(result) {
// ...
});
This works great but I only have the roleId associated to the user. I wasn't be able to link this "roleId" with the role table to get the other attributes like role name...
Here is the JSON I've got :
[
{
"id": 1,
"name": "Project name",
"users": [
{
"id": 1,
"name": "User name",
"role": {
"role": 1
}
}
]
}
]
But I would like to have something like that :
[
{
"id": 1,
"name": "Project name",
"users": [
{
"id": 1,
"name": "User name",
"role": {
"id": 1,
"name": "Role name",
"description": "Some info...",
}
}
]
}
]
I've tried many things to realize this association, even successive includes but it was unsuccessful. What is needed in the findAll options to get this JSON result ?
Thanks
Assuming that your User model is linked to the Role model, something like this should work:
models.Projects.findAll({
include:[
{
model: models.User,
as:'users',
through: {attributes: []},
include: [models.Role]
}] }).then(function(result) {
// ... });