How to perform join in sails JS - json

I have documents of the form
challenge:
{
"name": "challenge by abdul",
"created_user_id": "1",
"game_id": "123",
"platform_id": "9857",
"amount": 30
}
game:
{
"_id": "auto_generated",
"name": "NFS",
"version": "3",
}
platform:
{
"_id": "auto_generated",
"name": "ps2",
"version": "sami"
}
I want to perform join query in sails and want result in below format
{
"name": "challenge by abdul",
"created_user_id": "1",
"game_id": "123",
"game_name":"NFS",
"platform_name": "ps2",
"platform_id": "9857",
"amount": 30
}

There is no join in Sails but populate. So you need make associations between models and populate them. Example:
// api/models/Platform.js
module.exports = {
attributes: {
name: {
type: 'string'
},
version: {
type: 'string'
},
game: {
model: 'Game',
via: 'platform'
}
}
};
// api/models/Game.js
module.exports = {
attributes: {
name: {
type: 'string'
},
version: {
type: 'string'
},
platform: {
model: 'Platform',
via: 'game'
}
}
};
You can write following code then:
// api/controllers/AnyController.js
module.exports = {
index: function(req, res) {
Game
.findOne({name: 'MY_GAME'})
.populate('platform')
.then(function(game) {
console.log(game); // Game model
console.log(game.platform); // Platform model
return game;
})
.then(res.ok)
.catch(res.negotiate);
}
};

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));
}
});
}
});

Sequelize populate joined table attributes

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'
}]
}
]
});

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;
};

How would you handle two way relations in relational-pouch?

Is this schema valid in relational-pouch (especially the relations between obj and objList):
let schema = [
{
singular: 'obj', plural: 'objs', relations: {
'objList': { belongsTo: 'objList' },
'attributesEditable': { belongsTo: 'attributesEditable' },
'attributesViewable': { belongsTo: 'attributesViewable' },
},
},
{
singular: 'objList', plural: 'objLists', relations: {
'objs': { hasMany: 'obj' },
'obj': { belongsTo: 'obj' },
},
},
{
singular: 'attributesEditable', plural: 'attributesEditables', relations: {
'obj': { belongsTo: 'obj' },
},
},
{
singular: 'attributesViewable', plural: 'attributesViewables', relations: {
'obj': { belongsTo: 'obj' },
},
},
];
What I want:
My App starts with an entry point which is an obj and this has one objList with many obj in it and so on.
You have one realtion between objList and obj, and should declare it in both parts. But in objList declared two relations. Try this code:
[...]
{
singular: 'obj', plural: 'objs', relations: {
'objList': { belongsTo: 'objList' },
'attributesEditable': { belongsTo: 'attributesEditable' },
'attributesViewable': { belongsTo: 'attributesViewable' },
},
},
{
singular: 'objList', plural: 'objLists', relations: {
'objs': { hasMany: 'obj' }
},
[...]

Ember Data: Using "links" on JSON payload for hasMany relationships

Given two models in an app using DS.RESTAdapter:
App.Calendar = DS.Model.extend({
reservations: DS.hasMany("reservation", { async: true })
});
App.Reservation = DS.Model.extend({
date: DS.attr("date"),
calendar: DS.belongsTo("calendar")
});
And payloads such as:
/api/calendar/1:
{
"calendar": {
"id": 1,
"reservations": [],
"links": {
"reservations": "/api/calendar/1/reservations"
}
}
}
/api/calendar/1/reservations:
{
"reservations": [
{
"id": 1,
"date": "10/01/2014"
}
]
}
Why is it that the reservations array on the Calendar model isn't being lazy-loaded?
Your json shouldn't have reservations defined twice
{
"calendar": {
"id": 1,
"links": {
"reservations": "/api/calendar/1/reservations"
}
}
}