I am testing all the associations with sequelize and I am getting a problem to get joins for many to many with belongsToMany.
https://github.com/lhferrh/Sequelize-Playground.git
When I do the findAll through I get the all null for the join result
I have been checking several combinations but the thing is that the SQL produced by sequelize is working on MySQL directly and it makes me really confused.
This is the sql provided:
SELECT `user`.`userId`, `user`.`name`, `user`.`createdAt`, `user`.`updatedAt`, `cars`.`carId` AS `cars.carId`, `cars`.`make` AS `cars.make`, `cars`.`createdAt` AS `cars.createdAt`, `cars`.`updatedAt` AS `cars.updatedAt`, `cars->favorites`.`favoritesId` AS `cars.favorites.favoritesId`, `cars->favorites`.`date` AS `cars.favorites.date`, `cars->favorites`.`createdAt` AS `cars.favorites.createdAt`, `cars->favorites`.`updatedAt` AS `cars.favorites.updatedAt`, `cars->favorites`.`userId` AS `cars.favorites.userId`, `cars->favorites`.`carId` AS `cars.favorites.carId` FROM `users` AS `user` LEFT OUTER JOIN ( `favorites` AS `cars->favorites` INNER JOIN `cars` AS `cars` ON `cars`.`carId` = `cars->favorites`.`carId`) ON `user`.`userId` = `cars->favorites`.`userId`;
This is the code I am running:
const Users = sequelize.define('user', {
userId: {
type: Sequelize.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING,
},
}
);
const Favorites = sequelize.define('favorites', {
favoritesId: {
type: Sequelize.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
date: {
type: Sequelize.DATE,
}
}
);
const Cars = sequelize.define('cars', {
carId: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
make: Sequelize.STRING
})
Users.belongsToMany(Cars, {
through: 'favorites',
sourceKey: 'userId',
foreignKey: 'userId'
});
Cars.belongsToMany(Users, {
through: 'favorites',
sourceKey: 'carId',
foreignKey: 'carId'
});
const intiDataBase = async () => {
await sequelize.sync({force: true});
}
const run = async () => {
const max = 3;
await intiDataBase();
await Promise.all( DATA.users.map( async elem=>
Users.create({...elem})
))
await Promise.all( DATA.cars.map( async elem =>
Cars.create({...elem})
))
for( let i = 0 ; i < 5 ; i++ ){
Favorites.create({
userId: getRandomInt(1 , max),
carId: getRandomInt(0, max)
})
}
const car = await Users.findAll({
include: [{
model: Cars,
through: {
attributes: ['userId', 'carId'],
}
//attributes: ['make'],
}],
raw: true
});
const favorites = await Favorites.findAll({
where:{
userId:2
},
raw: true
});
console.log(car);
console.log(favorites);
}
run();
This is result I get:
name: 'Johan',
createdAt: 2019-10-05T08:57:57.000Z,
updatedAt: 2019-10-05T08:57:57.000Z,
'cars.carId': null,
'cars.make': null,
'cars.createdAt': null,
'cars.updatedAt': null,
'cars.favorites.favoritesId': null,
'cars.favorites.date': null,
'cars.favorites.createdAt': null,
'cars.favorites.updatedAt': null,
'cars.favorites.userId': null,
'cars.favorites.carId': null } ], ...
Probably this is a naming problem but the fact the SQL is working directly makes is really confusing.
I hope any of you can see the error.
By the way, I was also wondering what would be the disadvantage of creating the many to many relationship manually by creating two 1:m associations to the intermediate table?
I found my error. There is an await missing when I am inserting favorites to the database. For that reason the join was giving the the wrong result in the query and the correct one in the database directly.
for( let i = 0 ; i < 5 ; i++ ){
await Favorites.create({
userId: getRandomInt(1 , max),
carId: getRandomInt(0, max)
})
}
As I was expecting, a silly error.
Anyways I am still hesitant about using belongToMany or creating the many to many relationship by myself and use always two steps.
Related
I know this is a general question, but I have the following code in my app.js
app.post('/data', (req, res) =>{
const file = req.files.filename;
const nose = [];
const filename = file.name;
file.mv('./excel/'+filename, (err)=>{
if(err){
console.log(err)
} else{
const result = importExcel({
sourceFile: './excel/'+filename,
header: {rows:1},
columnToKey :{A:'Dimension', B:'Category', C:'Subcategory',D:'Factor', E:'Context', F:'Date',G:'Indicator', H:'Formula',I:'FoundValue'},
sheets:['data']
})
for(var i=0; result.data.length > i; i++){
nose.push(result.data[i].Dimension,
result.data[i].Category)
}
res.send(nose)
console.log(nose+' = Total data '+nose.length);
}
})
})
Here is my data.ejs in the part of the button for sending data
<form action="/data" method="post" enctype="multipart/form-data">
<div style="float:right">
<input style="margin-top:6%;" class="btn btn-light" type="file" name="filename">
<button style="float:right" type="submit" class="btn btn-success mt-4"><i class="fa-solid fa-file-import"></i></button>
</div>
<div class="footer" style="margin-left: 0px; margin-right: 0px!important;">
Right now it looks visually like this;
And my data is displayed like this;
Which is fine, because that's what my excel looks like;
Context: I need to send that .json data in app.js to my MySQL database using Nodejs but I don't know how to send that data to my database table, I've seen that they use multer,sequelize, etc. I don't know if that's the way or there are easier ways to understand for a newbie like me.
I also have an app. get, like this;
app.get('/data', (req, res) =>{
connection.query('SELECT c.data_id, d.dimension_name, cc.category_name, s.subcategory_name, f.factor_name,f.factor_description,c.date_creation_data, c.Indicator,ff.formula_name FROM data_load c INNER JOIN dimensions d ON c.dimension_id = d. id_dimensions INNER JOIN categories cc ON c.id_categories = cc.id_categories INNER JOIN subcategory s ON c.id_subcategories = s.id_subcategories INNER JOIN factors f ON c.id_factor = f.id_factor INNER JOIN formulas ff ON c.id_formula = ff.id_formula;',
function(error, results){
if(error){
console.log(error)
} else{
res.render('./data', {
results:results
})
}
})
})
My table, too, as you noticed in app.get has several INNER JOIN, so this is my table at present;
CREATE TABLE `carga_datos` (
`id_datos` int(11) NOT NULL,
`id_dimensiones` int(11) DEFAULT NULL,
`id_categorias` int(11) DEFAULT NULL,
`id_subcategorias` int(11) DEFAULT NULL,
`id_factor` int(11) DEFAULT NULL,
`fecha_creacion_data` timestamp NOT NULL DEFAULT current_timestamp(),
`Indicador` int(11) NOT NULL,
`id_formula` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `carga_datos`
ADD PRIMARY KEY (`id_datos`),
ADD KEY `id_dimensiones` (`id_dimensiones`),
ADD KEY `id_categorias` (`id_categorias`),
ADD KEY `id_subcategorias` (`id_subcategorias`),
ADD KEY `id_factor` (`id_factor`),
ADD KEY `id_formula` (`id_formula`);
ALTER TABLE `carga_datos`
MODIFY `id_datos` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
ALTER TABLE `carga_datos`
ADD CONSTRAINT `carga_datos_ibfk_1` FOREIGN KEY (`id_dimensiones`) REFERENCES `dimensiones` (`id_dimensiones`),
ADD CONSTRAINT `carga_datos_ibfk_2` FOREIGN KEY (`id_categorias`) REFERENCES `categorias` (`id_categorias`),
ADD CONSTRAINT `carga_datos_ibfk_3` FOREIGN KEY (`id_subcategorias`) REFERENCES `subcategoria` (`id_subcategorias`),
ADD CONSTRAINT `carga_datos_ibfk_4` FOREIGN KEY (`id_factor`) REFERENCES `factores` (`id_factor`),
ADD CONSTRAINT `carga_datos_ibfk_5` FOREIGN KEY (`id_formula`) REFERENCES `formulas` (`id_formula`);
COMMIT;
Please help, I don't know what to do,
Thanks in advance :(
I suggest using sequelize for your data models. This example should get you on your way.
You create and update tables via migrations, then run them via your console:
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('carga_datos', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
id_datos: {
allowNull: false,
type: Sequelize.INTEGER
},
id_dimensiones: {
allowNull: true,
type: Sequelize.INTEGER
},
id_categorias: {
allowNull: true,
type: Sequelize.INTEGER
},
id_subcategorias: {
allowNull: true,
type: Sequelize.INTEGER
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
})
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('carga_datos');
}
};
You will define your model schemas like this:
'use strict';
module.exports = (sequelize, DataTypes) => {
var carga_datos = sequelize.define('carga_datos', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
id_datos: {
allowNull: false,
type: DataTypes.INTEGER
},
id_dimensiones: {
allowNull: true,
type: DataTypes.INTEGER
},
id_categorias: {
allowNull: true,
type: DataTypes.INTEGER
},
id_subcategorias: {
allowNull: true,
type: DataTypes.INTEGER
},
createdAt: {
allowNull: false,
type: DataTypes.DATE
},
updatedAt: {
allowNull: false,
type: DataTypes.DATE
}
})
carga_datos.associate = function (models) {
}
return carga_datos;
}
When you want to create a new entry in your database, you will use:
const datos = await carga_datos.create({
id_datos: req.body.id_datos,
id_dimensiones: req.body.id_dimensiones
})
Pay attention to the types when writing models and migrations, they may get confused. Good luck!
I am trying to implement Sequelize as an ORM in NodeJs and I am using it for Mysql,
I have 3 tables in the sample -
1. Role
2. User (Has a role)
3. Code (IsCreated by a user)
I'm unable to query the tables/models properly,
As I should be receiving an model representation of a table, which is referred as a foreign key.
Following is my DB structure -
1. Role table -
2. User table -
3. Code table -
Following are the table creation queries -
1. Role -
CREATE TABLE role (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(100) NOT NULL,
PRIMARY KEY (id)
);
2. User -
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL,
`role` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `role` (`role`),
CONSTRAINT `user_ibfk_1` FOREIGN KEY (`role`) REFERENCES `role` (`id`)
);
3. Code -
CREATE TABLE `code` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`createdBy` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `createdBy` (`createdBy`),
CONSTRAINT `code_ibfk_1` FOREIGN KEY (`createdBy`) REFERENCES `user` (`id`)
);
Following is my app.js file -
const db = require('./db');
const Code = require('./code');
const User = require('./user');
const Role = require('./role');
const async = require('async');
async.waterfall([
function(callback) {
db
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
callback(null,"ok");
})
.catch(err => {
return callback(err,null);
});
},
function(resp,callback) {
Code.findAll({include: [{ model: User}]})
.then(code => {
console.log("All users:", JSON.stringify(code, null, 4));
callback(null,"ok");
})
.catch(err => {
callback(err,null);
});
// Code.findOne({
// where: {
// id: 1
// }
// })
// .then(code => {
// console.log("All users:", JSON.stringify(code, null, 4));
// })
// .catch(err => console.log("Error => \n",err));
},
],
function(err, resp) {
if (err) {
console.log(err);
} else {
console.log(resp);
}
});
Following is my db.js file -
const Sequelize = require('sequelize');
module.exports = new Sequelize('junit', 'root', 'root', {
host: 'localhost',
/* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */
dialect: 'mysql',
//operatorsAliases: false,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
});
Following is my role.js file -
const Sequelize = require('sequelize');
const db = require('./db');
const User = require('./user');
const Role = db.define('role', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
allowNull:false,
autoIncrement: true
},
name: {
type: Sequelize.STRING
}
}, {
tableName: 'role',
freezeTableName: true,
timestamps: false
});
associate : (models) => {
Role.hasMany(models.User,{
foreignKey: 'role'
});
};
module.exports = Role;
Following is my user.js file -
const Sequelize = require('sequelize');
const db = require('./db');
const Code = require('./code');
const Role = require('./role');
const User = db.define('user', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
allowNull:false,
autoIncrement: true
},
name: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
role: {
type: Sequelize.INTEGER,
references: {
// This is a reference to another model
model: Role,
// This is the column name of the referenced model
key: 'id'
}
}
}, {
tableName: 'user',
freezeTableName: true,
timestamps: false
});
associate : (models) => {
User.hasMany(models.Code,{
foreignKey: 'createdBy'
});
User.belongsTo(models.Role,{
foreignKey: 'role'
});
};
module.exports = User;
Following is my code.js file -
const Sequelize = require('sequelize');
const db = require('./db');
const User = require('./user');
//one-to-many
const Code = db.define('code', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
allowNull:false,
autoIncrement: true
},
name: {
type: Sequelize.STRING
},
// createdBy: {
// type: Sequelize.INTEGER
// },
createdBy: {
type: Sequelize.INTEGER,
references: {
// This is a reference to another model
model: User,
// This is the column name of the referenced model
key: 'id'
}
}
}, {
tableName: 'code',
freezeTableName: true,
timestamps: false
});
associate : (models) => {
Code.belongsTo(models.User,{
foreignKey: 'createdBy'
});
};
module.exports = Code;
When I run the app.js file I can't see the model reference of User,
But I get the usual Integer value, Can someone please help on how to properly use the Model here?
Error trace -
Looks like you're trying to fetch Code when connection wasn't established yet.
Try this:
const db = require('./db');
const Code = require('./code');
const User = require('./user');
const Role = require('./role');
function run() {
return db
.authenticate()
.then(() => Code.findOne({ // you can try execute whenever query you want here
where: {
id: 1
}})
.then(code => {
console.log("All users:", JSON.stringify(code, null, 4));
})
.catch(err => console.log("Error => \n",err)))
.catch(err => {
console.error('Unable to connect to the database:', err);
});
}
run();
Im having problems associating 2 models. I will try to describe the problem as detailed as possible and hope you can help me.
I have 2 Models: Zone and PLZ (both are also tables in database-mysql).
There can be One Zone having many PLZs and one PLZ can belong to One zone.
On saving a zone with its PLZs I have a table called "zone_plz" with only two columns: zone_id and plz_id. Both have foreign keys to Zone.id and PLZ.id
Zone Model:
const Sequelize = require('sequelize');
const sequelize = require('../util/database');
const PLZ = require('../models/PLZ');
const zone_plz = require('../models/relations/zone_plzs');
const Zone = sequelize.define('zone', {
name: {
type: Sequelize.STRING,
allowNull: false
},
color: {
type: Sequelize.STRING,
allowNull: false
}
}, {
timestamps: true
});
module.exports = Zone;
PLZ model:
const Sequelize = require('sequelize');
const sequelize = require('../util/database');
const Zone = require('../models/Zone');
const zone_plz = require('../models/relations/zone_plzs');
const PLZ = sequelize.define('plz', {
plz: {
type: Sequelize.INTEGER,
allowNull: false
},
city: {
type: Sequelize.STRING,
allowNull: false
},
district: {
type: Sequelize.STRING
}
});
module.exports = PLZ;
and this is the zone_plz model:
const Sequelize = require('sequelize');
const sequelize = require('../../util/database');
const PLZ = require('../../models/PLZ');
const Zone = require('../../models/Zone');
const zone_plz = sequelize.define('zone_plz', {
zone_id: {
type: Sequelize.INTEGER,
allowNull: false,
references: {
model: Zone,
key: 'id',
}
},
plz_id: {
type: Sequelize.INTEGER,
allowNull: false,
references: {
model: PLZ,
key: 'id',
}
}
}, {
timestamps: true
});
module.exports = zone_plz;
and this is how I query it:
router.get('/', function (req, res, next) {
zone_plz.findAll({
include: [{
model: PLZ,
as: 'plz'
},
{
model: Zone,
as: 'zone'
}]
}).then((result) => {
res.send({status: true, data: result})
}).catch(function (err) {
next(err)
})
});
As you can see i want to return a zone with all the belonging plzs to the user.
Im new to sequelize and Im also not sure if this is the right approach. I get the error: plz is not associated to zone_plz!
Can anyone help me?
You created references, not associations. Please, first of all, read the differences: Sequelize model references vs associations
then create associations between plz & zone like:
plz.belongsToMany(zone, {through: 'zone_plz'});
zone.belongsToMany(plz, {through: 'zone_plz'});
I have got a many-to-many relationship between two models, users and groups.
I have two models which are specifying the belongsToMany with a foreignKey and through attribute.
Users model
'use strict';
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define('User', {
firstName: DataTypes.STRING,
lastName: DataTypes.STRING,
email: DataTypes.STRING,
username: DataTypes.STRING,
facebookId: DataTypes.STRING,
password: DataTypes.STRING,
}, {
classMethods: {
associate: function(models) {
User.hasMany(models.Payment);
User.hasMany(models.Friend, {foreignKey: 'userIdLink1'});
User.belongsToMany(models.Group, { through: 'UsersGroups', foreignKey: 'facebookId' });
}
},
instanceMethods: {
toJSON: function () {
var values = Object.assign({}, this.get());
delete values.password;
return values;
}
}
});
return User;
};
groups model
'use strict';
module.exports = function(sequelize, DataTypes) {
var Group = sequelize.define('Group', {
name: DataTypes.STRING
}, {
classMethods: {
associate: function(models) {
// associations can be defined here
Group.belongsToMany(models.User, {through: 'UsersGroups', foreignKey: 'groupId'});
Group.hasMany(models.Payment)
}
},
instanceMethods: {
toJSON: function () {
var values = Object.assign({}, this.get());
delete values.password;
return values;
}
}
});
return Group;
};
which are being joined via a junction table UsersGroups
This works fine and I can create a new group and it links the user with it successfully but when I try fetch the data the SQL query is trying to find Groups based on User.id as opposed to User.facebookId like I specified in my model User.belongsToMany(models.Group, { through: 'UsersGroups', foreignKey: 'facebookId' });
I call the following code to fetch the data:
const options = {
where: {
facebookId: facebookId,
},
defaults: {
firstName: data.firstName,
lastName: data.lastName,
email: data.email,
facebookId: facebookId
},
include: [
{ model: db.Group }
]
}
db.User.findOrCreate(options)
.then((user) => {
res.send(user)
}, (err) => {
res.status(500).send(err)
})
and it returns a user but with an empty Groups array which is incorrect as there is definitely data there as I can create it fine and see it in the DB.
You can see the SQL query that is generated by Sequelize here:
SELECT `User`.*, `Groups`.`id` AS `Groups.id`, `Groups`.`name` AS `Groups.name`, `Groups`.`createdAt` AS `Groups.createdAt`, `Groups`.`updatedAt` AS `Groups.updatedAt`, `Groups.UsersGroups`.`createdAt` AS `Groups.UsersGroups.createdAt`, `Groups.UsersGroups`.`updatedAt` AS `Groups.UsersGroups.updatedAt`, `Groups.UsersGroups`.`facebookId` AS `Groups.UsersGroups.facebookId`, `Groups.UsersGroups`.`groupId` AS `Groups.UsersGroups.groupId`
FROM (
SELECT `User`.`id`, `User`.`firstName`, `User`.`lastName`, `User`.`email`, `User`.`username`, `User`.`facebookId`, `User`.`password`, `User`.`createdAt`, `User`.`updatedAt` FROM `Users` AS `User` WHERE `User`.`facebookId` = '1341052992643877' LIMIT 1) AS `User`
LEFT OUTER JOIN (`UsersGroups` AS `Groups.UsersGroups`
INNER JOIN `Groups` AS `Groups` ON `Groups`.`id` = `Groups.UsersGroups`.`groupId`
)
ON `User`.`id` = `Groups.UsersGroups`.`facebookId`;
Note the last line
ON `User`.`id` = `Groups.UsersGroups`.`facebookId`
needs to be
ON `User`.`facebookId` = `Groups.UsersGroups`.`facebookId`
Turns out I had to specify facebookId as a primary key in my user model
facebookId: {
type: DataTypes.STRING,
primaryKey: true,
},
I am using sequelize as my backend ORM.
But I have a problem when I want "where" with a join table. The associations are good but I didn't know how to do for the "where".
This my code :
router.get('/id_presta_struct_unit/:id_presta_struct_unit', (req, res) => {
models.structures.findAll({
include: {
required: false,
model: models.structures_proposer_prestations,
where: {
id_presta_struct_unit: req.params.id_presta_struct_unit
},
include: {
model : models.unites_facturation,
}
}
}).then(data => {
res.writeHead(200, {'Content-Type': 'application/json; charset=utf-8'});
res.end(JSON.stringify(data));
});
});
I got this request
SELECT * FROM structures AS structures LEFT OUTER JOIN structures_proposer_prestations AS structures_proposer_prestations ON structures.id_structure = structures_proposer_prestations.id_structure AND structures_proposer_prestations.id_presta_struct_unit = '1' LEFT OUTER JOIN unites_facturation AS structures_proposer_prestations.unites_facturation ON structures_proposer_prestations.id_unite = structures_proposer_prestations.unites_facturation.id_unite;
But i would like to get
SELECT * FROM structures AS structures LEFT OUTER JOIN structures_proposer_prestations AS structures_proposer_prestations ON structures.id_structure = structures_proposer_prestations.id_structure LEFT OUTER JOIN unites_facturation AS structures_proposer_prestations.unites_facturation ON structures_proposer_prestations.id_unite = structures_proposer_prestations.unites_facturation.id_unite WHERE structures_proposer_prestations.id_presta_struct_unit = '1';
I don't know what to do I didn't find a post with the same problem
Can anyone point me in the right direction?
Thank you in advance.
Edit:
The associations
models.structures_employer_ressources.hasMany(models.ressources, { foreignKey: 'id_ressource' });
models.ressources.belongsTo(models.structures_employer_ressources, { foreignKey: 'id_ressource' });
The model of ressources
module.exports = function(sequelize, DataTypes) {
return sequelize.define('ressources', {
id_ressource: {
type: DataTypes.STRING,
allowNull: false,
primaryKey: true
}
........
},{
tableName: 'ressources',
updatedAt: 'date_modification',
createdAt: 'date_creation'
});
};
And the model of structures_employer_ressources
module.exports = function(sequelize, DataTypes) {
return sequelize.define('structures_employer_ressources', {
id_structure: {
type: DataTypes.STRING,
allowNull: false,
primaryKey: true,
references: {
model :'structures',
key: 'id_structure'
}
},
id_ressource: {
type: DataTypes.STRING,
allowNull: false,
primaryKey: true,
references: {
model :'ressources',
key: 'id_ressource'
}
}
},{
tableName: 'structures_employer_ressources',
updatedAt: 'date_modification',
createdAt: 'date_creation'
});
};
If you feed an array into the where clause of the initial join, you can run a raw query against the joins.
Example:
models.structures.findAll({
where:[["[structures_proposer_prestations].[id_presta_struct_unit] = " + req.params.id_presta_struct_unit, null]],
include: {
required: false,
model: models.structures_proposer_prestations,
where: {
id_presta_struct_unit: req.params.id_presta_struct_unit
},
include: {
model : models.unites_facturation,
}
}
}
The array can also take in standard object syntax and will be combined by an AND. The null I am passing in is for paramaters, so It can definitely be optimised to take in the id as a paramater, just don't know the syntax off hand.