New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

mappifysql

Package Overview
Dependencies
Maintainers
0
Versions
17
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mappifysql - npm Package Compare versions

Comparing version 1.1.2 to 1.1.3

817

app.d.ts

@@ -9,396 +9,517 @@ /**

/**
* Model class for managing database records.
* @example class User extends MappifyModel {}
*/
export class MappifyModel {
/**
* Model class for managing database records.
* @example class User extends MappifyModel {}
*/
export class MappifyModel {
/**
* This static getter returns the table name for the model, which is the pluralized, lowercased class name.
* @example User.tableName // returns 'users'
* @example using in static functions method -> this.tableName
* @example using in instance functions method -> this.constructor.tableName
* @returns {string} The table name.
*/
static tableName(): string;
* This static getter returns the table name for the model, which is the pluralized, lowercased class name.
* @example User.tableName // returns 'users'
* @example using in static functions method -> this.tableName
* @example using in instance functions method -> this.constructor.tableName
* @returns {string} The table name.
*/
static get tableName(): string;
/**
* This method sets properties on the instance from a given object.
* @example user.setProperties({ name: 'John Doe', email: 'user@example.com' });
* @param {object} properties - The properties to set.
*/
setProperties(properties: object): void;
/**
* This method sets properties on the instance from a given object.
* @example user.setProperties({ name: 'John Doe', email: 'user@example.com' });
* @param {object} properties - The properties to set.
*/
setProperties(properties: object): void;
/**
* This method is used to define associations between models.
* @example class Post extends MappifyModel {
* associations() {
* this.belongsTo(User, {
* as: 'user',
* key: 'id',
* foreignKey: 'user_id'
* });
* }
* }
*/
associations(): void;
/**
* This method is used to define associations between models.
* @example class Post extends MappifyModel {
* associations() {
* this.belongsTo(User, {
* as: 'user',
* key: 'id',
* foreignKey: 'user_id'
* });
* }
* }
*/
associations(): void;
/**
* This method is used to define a one-to-one relationship between two models.
* @param {Model} relatedModel - The related model.
* @param {object} options - The options for the association.
* @param {string} options.as - The alias for the association.
* @param {string} options.foreignKey - The foreign key in this model.
* @example const ShippingAddress = require('path/to/shippingaddressmodel');
* class Order extends MappifyModel {
* associations() {
* this.hasOne(ShippingAddress, {
* as: 'shippingAddress',
* foreignKey: 'order_id'
* });
* }
* }
*/
hasOne(relatedModel: MappifyModel, options: object): void;
/**
* This method is used to define a one-to-one relationship between two models.
* @param {Model} relatedModel - The related model.
* @param {object} options - The options for the association.
* @param {string} options.as - The alias for the association.
* @param {string} options.foreignKey - The foreign key in this model.
* @example const ShippingAddress = require('path/to/shippingaddressmodel');
* class Order extends MappifyModel {
* associations() {
* this.hasOne(ShippingAddress, {
* as: 'shippingAddress',
* foreignKey: 'order_id'
* });
* }
* }
*/
hasOne(relatedModel: Class, options: object): void;
/**
* This method is used to define a one-to-one relationship between two models.
* @param {Model} relatedModel - The related model.
* @param {object} options - The options for the association.
* @param {string} options.as - The alias for the association.
* @param {string} options.key - The primary key in the related model.
* @param {string} options.foreignKey - The foreign key in this model.
* @example const Order = require('path/to/ordermodel');
* class ShippingAddress extends MappifyModel {
* associations() {
* this.belongsTo(Order, {
* as: 'order',
* key: 'id',
* foreignKey: 'order_id'
* });
* }
* }
* @example const Student = require('path/to/studentmodel');
* const Course = require('path/to/coursemodel');
* class Enrollment extends MappifyModel {
* associations() {
* this.belongsTo(Student, {
* as: 'student',
* key: 'id',
* foreignKey: 'student_id'
* });
* this.belongsTo(Course, {
* as: 'course',
* key: 'id',
* foreignKey: 'course_id'
* });
* }
* }
*/
belongsTo(relatedModel: MappifyModel, options: object): void;
/**
* This method is used to define a one-to-many relationship between two models.
* @param {Model} relatedModel - The related model.
* @param {object} options - The options for the association.
* @param {string} options.as - The alias for the association.
* @param {string} options.foreignKey - The foreign key in the related model.
* @example const User = require('path/to/usermodel');
* class Post extends MappifyModel {
* associations() {
* this.hasMany(User, {
* as: 'user',
* foreignKey: 'post_id'
* });
* }
* }
*/
hasMany(relatedModel: MappifyModel, options: object): void;
/**
* This method is used to define a one-to-one relationship between two models.
* @param {Model} relatedModel - The related model.
* @param {object} options - The options for the association.
* @param {string} options.as - The alias for the association.
* @param {string} options.key - The primary key in the related model.
* @param {string} options.foreignKey - The foreign key in this model.
* @example const Order = require('path/to/ordermodel');
* class ShippingAddress extends MappifyModel {
* associations() {
* this.belongsTo(Order, {
* as: 'order',
* key: 'id',
* foreignKey: 'order_id'
* });
* }
* }
* @example const Student = require('path/to/studentmodel');
* const Course = require('path/to/coursemodel');
* class Enrollment extends MappifyModel {
* associations() {
* this.belongsTo(Student, {
* as: 'student',
* key: 'id',
* foreignKey: 'student_id'
* });
* this.belongsTo(Course, {
* as: 'course',
* key: 'id',
* foreignKey: 'course_id'
* });
* }
* }
*/
belongsTo(relatedModel: Class, options: object): void;
/**
* This method is used to define a many-to-many relationship between two models.
* @param {Model} relatedModel - The related model.
* @param {object} options - The options for the association.
* @param {string} options.as - The alias for the association.
* @param {string} options.through - The "join" table that connects the two models. i.e., the table that stores the foreign keys of the two models.
* @param {string} options.key - The primary key in the related model.
* @param {string} options.foreignKey - The foreign key in through model for this model.
* @param {string} options.otherKey - The foreign key in through model for the related model.
* @example const Enrollment = require('path/to/enrollmentmodel');
* const Course = require('path/to/coursemodel');
* class Student extends MappifyModel {
* associations() {
* this.belongsToMany(Course, {
* as: 'courses',
* through: Enrollment,
* key: 'id',
* foreignKey: 'student_id',
* otherKey: 'course_id'
* });
* }
* }
* @example const Enrollment = require('path/to/enrollmentmodel');
* const Student = require('path/to/studentmodel');
* class Course extends MappifyModel {
* associations() {
* this.belongsToMany(Student, {
* as: 'students',
* through: Enrollment,
* key: 'id',
* foreignKey: 'course_id',
* otherKey: 'student_id'
* });
* }
* }
*/
belongsToMany(relatedModel: MappifyModel, options: object): void;
/**
* This method is used to define a one-to-many relationship between two models.
* @param {Model} relatedModel - The related model.
* @param {object} options - The options for the association.
* @param {string} options.as - The alias for the association.
* @param {string} options.foreignKey - The foreign key in the related model.
* @example const User = require('path/to/usermodel');
* class Post extends MappifyModel {
* associations() {
* this.hasMany(User, {
* as: 'user',
* foreignKey: 'post_id'
* });
* }
* }
*/
hasMany(relatedModel: Class, options: object): void;
/**
* This method fetches the related data for a given relation.
* @param {string} relation - The name of the relation to populate.
* @param {object} options - The options for the query. - (optional)
* @param {Array} options.attributes - The columns to include in the result. - (optional)
* @param {Array} options.exclude - The columns to exclude from the result. - (optional)
* @example const post = await Post.findById(1);
* await post.populate('user');
* console.log(post.user);
* @example const student = await Student.findById(1);
* await student.populate('courses');
* console.log(student.courses);
* @example const course = await Course.findById(1);
* @example const course = await Course.findById(1);
* await course.populate('students', { exclude: ['created_at', 'updated_at'] });
* console.log(course.students);
* @example const enrollment = await Enrollment.findById(1);
* await enrollment.populate('student', { exclude: ['created_at', 'updated_at'] });
* await enrollment.populate('course', { attributes: ['name', 'description'] });
* console.log(enrollment.student);
* console.log(enrollment.course);
* @returns {this} The instance of the model with the populated relation.
*/
populate(relation: string, options: object): this;
/**
* This method is used to define a many-to-many relationship between two models.
* @param {Model} relatedModel - The related model.
* @param {object} options - The options for the association.
* @param {string} options.as - The alias for the association.
* @param {string} options.through - The "join" table that connects the two models. i.e., the table that stores the foreign keys of the two models.
* @param {string} options.key - The primary key in the related model.
* @param {string} options.foreignKey - The foreign key in through model for this model.
* @param {string} options.otherKey - The foreign key in through model for the related model.
* @example const Enrollment = require('path/to/enrollmentmodel');
* const Course = require('path/to/coursemodel');
* class Student extends MappifyModel {
* associations() {
* this.belongsToMany(Course, {
* as: 'courses',
* through: Enrollment,
* key: 'id',
* foreignKey: 'student_id',
* otherKey: 'course_id'
* });
* }
* }
* @example const Enrollment = require('path/to/enrollmentmodel');
* const Student = require('path/to/studentmodel');
* class Course extends MappifyModel {
* associations() {
* this.belongsToMany(Student, {
* as: 'students',
* through: Enrollment,
* key: 'id',
* foreignKey: 'course_id',
* otherKey: 'student_id'
* });
* }
* }
*/
belongsToMany(relatedModel: Class, options: object): void;
/**
* This method saves the instance to the database.
* @example const product = new Product({ name: 'Product 1', price: 100 });
* await product.save();
* @returns {Promise<number>} The ID of the inserted record.
*/
save(): Promise<number>;
/**
* This method fetches the related data for a given relation.
* @param {string} relation - The name of the relation to populate.
* @param {object} options - The options for the query. - (optional)
* @param {Array} options.attributes - The columns to include in the result. - (optional)
* @param {Array} options.exclude - The columns to exclude from the result. - (optional)
* @example const post = await Post.findById(1);
* await post.populate('user');
* console.log(post.user);
* @example const student = await Student.findById(1);
* await student.populate('courses');
* console.log(student.courses);
* @example const course = await Course.findById(1);
* @example const course = await Course.findById(1);
* await course.populate('students', { exclude: ['created_at', 'updated_at'] });
* console.log(course.students);
* @example const enrollment = await Enrollment.findById(1);
* await enrollment.populate('student', { exclude: ['created_at', 'updated_at'] });
* await enrollment.populate('course', { attributes: ['name', 'description'] });
* console.log(enrollment.student);
* console.log(enrollment.course);
* @returns {this} The instance of the model with the populated relation.
*/
populate(relation: string, options?: object): Promise<this>;
/**
* This method updates the instance in the database.
* @example var product = await Product.findById(1);
* product.price = 200;
* await product.update();
* @returns {Promise<boolean>} A promise that resolves to true if the record was updated, otherwise false.
*/
update(): Promise<boolean>;
/**
* This method attaches a new record to the related model and associates it with the current instance.
* @param {Model} target - The record to attach to the relation.
* @param {string} relation - The name of the relation to attach to.
* @param {object} options - The options for the query. - (optional)
* @param {Array} options.attributes - The columns to include in the result. - (optional)
* @param {Array} options.exclude - The columns to exclude from the result. - (optional)
* @example const user = await User.findById(1);
* const post = new Post({ title: 'Post 1', content: 'This is post 1' });
* await user.attach(post, 'posts');
* console.log(user);
* @example const order = await Order.findOne({ where: { id: 1 } });
* const shippingAddress = new ShippingAddress({ address: '123 Main St', city: 'Springfield', state: 'IL', zip: '62701' });
* await order.attach(shippingAddress, 'shippingAddress');
* console.log(order);
*@returns {Promise<this>} A promise that resolves to the instance with the related data attached.
* @throws {Error} Throws an error if the relation is not defined.
* @throws {Error} Throws an error if the relation is not a hasOne or hasMany relation.
* @throws {Error} Throws an error if the foreign key is not defined.
*/
attach(target: Model, relation: string, options?: object): Promise<this>;
/**
* This method deletes the instance from the database.
* @example var product = await Product.findById(1);
* await product.delete();
* @returns {Promise<boolean>} A promise that resolves to true if the record was deleted, otherwise false.
*/
delete(): Promise<boolean>;
/**
* This method saves the instance to the database.
* @example const product = new Product({ name: 'Product 1', price: 100 });
* await product.save();
* @returns {Promise<number>} The ID of the inserted record.
*/
save(): Promise<number>;
/**
* This method fetches all records from the database.
* @example var products = await Product.fetch();
* @returns {Promise<Array<Model>>} An array of instances.
*/
static fetch(): Promise<Array<MappifyModel>>;
/**
* This method updates the instance in the database.
* @example var product = await Product.findById(1);
* product.price = 200;
* await product.update();
* @returns {Promise<boolean>} A promise that resolves to true if the record was updated, otherwise false.
*/
update(): Promise<boolean>;
/**
* This static method fetches one record from the table based on the provided options.
* @param {object} options - The options for the query.
* @param {object} options.where - The WHERE clause for the query.
* @param {Array} options.exclude - The columns to exclude from the result.
* @param {Array} options.attributes - The columns to include in the result.
* @example var product = await Product.findOne({ where: { id: 1 } });
* @example var product = await Product.findOne({ where: { name: 'Product 1' }, exclude: ['created_at', 'updated_at'] });
* @example var product = await Product.findOne({ where: { price: { gt: 100 } }, attributes: ['name', 'price'] });
* @example var product = await Product.findOne({ where: { price: { gt: 100, lt: 200 } } });
* @example var product = await Product.findOne({ where: { price: { in: [100, 200] } } });
* @example var product = await Product.findOne({ where: { price: { notIn: [100, 200] } } });
* @example var product = await Product.findOne({ where: { price: { between: [100, 200] } } });
* @example var product = await Product.findOne({ where: { price: { notBetween: [100, 200] } } });
* @example var product = await Product.findOne({ where: { name: { like: 'Product%' } } });
* @example var product = await Product.findOne({ where: { name: { notLike: 'Product%' } } });
* @example var product = await Product.findOne({ where: { name: { isNull: true } } });
* @example var product = await Product.findOne({ where: { name: { isNotNull: true } } });
* @example var product = await Product.findOne({ where: { not: { name: 'Product 1' } } });
* @example var product = await Product.findOne({ where: { and: [{ name: 'Product 1' }, { price: 100 }] } });
* @example var product = await Product.findOne({ where: { or: [{ name: 'Product 1' }, { price: 100 }] } });
* @returns {Promise<Array|null>} An instance of an array or null if no record was found.
*/
static findOne(options: object): Promise<Array<MappifyModel>>;
/**
* This method deletes the instance from the database.
* @example var product = await Product.findById(1);
* await product.delete();
* @returns {Promise<boolean>} A promise that resolves to true if the record was deleted, otherwise false.
*/
delete(): Promise<boolean>;
/**
* This static method fetches one record from the table based on the provided ID.
* @param {number} id - The ID of the record to fetch.
* @example var product = await Product.findById(1);
* console.log(product);
* @returns {Promise<Array|null>} An instance of an array or null if no record was found.
*/
static findById(id: number): Promise<Array<MappifyModel>>;
/**
* This method fetches all records from the database.
* @example var products = await Product.fetch();
* @returns {Promise<Array<Model>>} An array of instances.
*/
static fetch(): Promise<Array<MappifyModel>>;
/**
* This static method fetches all records from the table based on the provided options.
* @param {object} options - The options for the query.
* @param {object} options.where - The WHERE clause for the query.
* @param {Array} options.exclude - The columns to exclude from the result.
* @param {Array} options.attributes - The columns to include in the result.
* @param {number} options.limit - The maximum number of records to fetch.
* @param {number} options.offset - The number of records to skip.
* @param {string} options.order - The column to order the results by.
* @param {string} options.group - The column to group the results by.
* @example var products = await Product.findAll();
* @example var products = await Product.findAll({ where: { price: { gt: 100 } } });
* @example var products = await Product.findAll({ where: { price: { gt: 100, lt: 200 } } });
* @example var products = await Product.findAll({ where: { price: { in: [100, 200] } } });
* @example var products = await Product.findAll({ where: { price: { notIn: [100, 200] } } });
* @example var products = await Product.findAll({ where: { price: { between: [100, 200] } } });
* @example var products = await Product.findAll({ where: { price: { notBetween: [100, 200] } } });
* @example var products = await Product.findAll({ where: { name: { like: 'Product%' } } });
* @example var products = await Product.findAll({ where: { name: { notLike: 'Product%' } } });
* @example var products = await Product.findAll({ where: { name: { isNull: true } } });
* @example var products = await Product.findAll({ where: { name: { isNotNull: true } } });
* @example var products = await Product.findAll({ where: { not: { name: 'Product 1' } } });
* @example var products = await Product.findAll({ where: { and: [{ name: 'Product 1' }, { price: 100 }] } });
* @example var products = await Product.findAll({ where: { or: [{ name: 'Product 1' }, { price: 100 }] } });
* @example var products = await Product.findAll({ exclude: ['created_at', 'updated_at'] });
* @example var products = await Product.findAll({ attributes: ['name', 'price'] });
* @example var products = await Product.findAll({ limit: 10, offset: 0 });
* @example var products = await Product.findAll({ order: 'price DESC' });
* @example var products = await Product.findAll({ group: 'category' });
* @returns {Promise<Array<Model>>} An array of instances.
*/
static findAll(options: object): Promise<Array<MappifyModel>>;
/**
* This static method fetches one record from the table based on the provided options.
* @param {object} options - The options for the query.
* @param {object} options.where - The WHERE clause for the query.
* @param {Array} options.exclude - The columns to exclude from the result.
* @param {Array} options.attributes - The columns to include in the result.
* @example var product = await Product.findOne({ where: { id: 1 } });
* @example var product = await Product.findOne({ where: { name: 'Product 1' }, exclude: ['created_at', 'updated_at'] });
* @example var product = await Product.findOne({ where: { price: { gt: 100 } }, attributes: ['name', 'price'] });
* @example var product = await Product.findOne({ where: { price: { gt: 100, lt: 200 } } });
* @example var product = await Product.findOne({ where: { price: { in: [100, 200] } } });
* @example var product = await Product.findOne({ where: { price: { notIn: [100, 200] } } });
* @example var product = await Product.findOne({ where: { price: { between: [100, 200] } } });
* @example var product = await Product.findOne({ where: { price: { notBetween: [100, 200] } } });
* @example var product = await Product.findOne({ where: { name: { like: 'Product%' } } });
* @example var product = await Product.findOne({ where: { name: { notLike: 'Product%' } } });
* @example var product = await Product.findOne({ where: { name: { isNull: true } } });
* @example var product = await Product.findOne({ where: { name: { isNotNull: true } } });
* @example var product = await Product.findOne({ where: { not: { name: 'Product 1' } } });
* @example var product = await Product.findOne({ where: { and: [{ name: 'Product 1' }, { price: 100 }] } });
* @example var product = await Product.findOne({ where: { or: [{ name: 'Product 1' }, { price: 100 }] } });
* @returns {Promise<Object|null>} An instance of an array or null if no record was found.
*/
static findOne(options: object): Promise<Object<MappifyModel>>;
/**
* This static method finds a record based on the provided options, or creates a new record if no record is found.
* @param {object} options - The options for the query.
* @param {object} data - The data to create the record with.
* @example var user = await User.findOrCreate({ where: { email: 'user@example.com' } }, { name: 'John Doe', password: 'password' });
* @returns {Promise<{ instance: Model, created: boolean }>} An object containing the instance and a boolean indicating if the record was created.
* @throws {Error} Throws an error if the where clause is not provided.
*/
static findOrCreate(options: object, data: object): Promise<{ instance: MappifyModel, created: boolean }>;
/**
* This static method fetches one record from the table based on the provided ID.
* @param {number} id - The ID of the record to fetch.
* @example var product = await Product.findById(1);
* console.log(product);
* @returns {Promise<Object|null>} An instance of an array or null if no record was found.
*/
static findById(id: number): Promise<Object<MappifyModel>>;
/**
* This static method deletes a record from the table based on its ID.
* @param {number} id - The ID of the record to delete.
* @example await User.findByIdAndDelete(1);
* @returns {Promise<boolean>} A promise that resolves to true if the record was deleted, otherwise false.
* @throws {Error} Throws an error if the ID is not provided or if no record is found.
* @example await User.findByIdAndDelete(1);
*/
static findByIdAndDelete(id: number): Promise<boolean>;
/**
* This static method fetches all records from the table based on the provided options.
* @param {object} options - The options for the query.
* @param {object} options.where - The WHERE clause for the query.
* @param {Array} options.exclude - The columns to exclude from the result.
* @param {Array} options.attributes - The columns to include in the result.
* @param {number} options.limit - The maximum number of records to fetch.
* @param {number} options.offset - The number of records to skip.
* @param {string} options.order - The column to order the results by.
* @param {string} options.group - The column to group the results by.
* @example var products = await Product.findAll();
* @example var products = await Product.findAll({ where: { price: { gt: 100 } } });
* @example var products = await Product.findAll({ where: { price: { gt: 100, lt: 200 } } });
* @example var products = await Product.findAll({ where: { price: { in: [100, 200] } } });
* @example var products = await Product.findAll({ where: { price: { notIn: [100, 200] } } });
* @example var products = await Product.findAll({ where: { price: { between: [100, 200] } } });
* @example var products = await Product.findAll({ where: { price: { notBetween: [100, 200] } } });
* @example var products = await Product.findAll({ where: { name: { like: 'Product%' } } });
* @example var products = await Product.findAll({ where: { name: { notLike: 'Product%' } } });
* @example var products = await Product.findAll({ where: { name: { isNull: true } } });
* @example var products = await Product.findAll({ where: { name: { isNotNull: true } } });
* @example var products = await Product.findAll({ where: { not: { name: 'Product 1' } } });
* @example var products = await Product.findAll({ where: { and: [{ name: 'Product 1' }, { price: 100 }] } });
* @example var products = await Product.findAll({ where: { or: [{ name: 'Product 1' }, { price: 100 }] } });
* @example var products = await Product.findAll({ exclude: ['created_at', 'updated_at'] });
* @example var products = await Product.findAll({ attributes: ['name', 'price'] });
* @example var products = await Product.findAll({ limit: 10, offset: 0 });
* @example var products = await Product.findAll({ order: 'price DESC' });
* @example var products = await Product.findAll({ group: 'category' });
* @returns {Promise<Array<Model>>} An array of instances.
*/
static findAll(options?: object): Promise<Array<MappifyModel>>;
/**
* This static method updates a record in the table based on the provided options.
* @param {object} options - The options for the query.
* @param {object} options.where - The WHERE clause for the query.
* @param {object} data - The new data for the record.
* @example await Product.findOneAndDelete({ where: { name: 'Product 1' } });
* @returns {Promise<Model|null>} The updated instance or null if no record was found.
* @throws {Error} Throws an error if the where clause is not provided or if no record is found.
*/
static findOneAndDelete(options: object): Promise<MappifyModel>;
/**
* This static method finds a record based on the provided options, or creates a new record if no record is found.
* @param {object} options - The options for the query.
* @param {object} data - The data to create the record with.
* @example var user = await User.findOrCreate({ where: { email: 'user@example.com' } }, { name: 'John Doe', password: 'password' });
* @returns {Promise<{ instance: Model, created: boolean }>} An object containing the instance and a boolean indicating if the record was created.
* @throws {Error} Throws an error if the where clause is not provided.
*/
static findOrCreate(options: object, data: object): Promise<{ instance: MappifyModel, created: boolean }>;
/**
* This static method updates a record in the table based on the provided options.
* @param {object} options - The options for the query.
* @param {object} options.where - The WHERE clause for the query.
* @param {object} options.attributes - The columns to include in the result.
* @param {object} options.exclude - The columns to exclude from the result.
* @param {object} data - The new data for the record.
* @example await Product.findOneAndUpdate({ where: { id: 1 } }, { price: 200 });
* @returns {Promise<Model|null>} The updated instance or null if no record was found.
* @throws {Error} Throws an error if the where clause is not provided or if no record is found.
*/
static findOneAndUpdate(options: object, data: object): Promise<MappifyModel>;
/**
* This static method deletes a record from the table based on its ID.
* @param {number} id - The ID of the record to delete.
* @example await User.findByIdAndDelete(1);
* @returns {Promise<boolean>} A promise that resolves to true if the record was deleted, otherwise false.
* @throws {Error} Throws an error if the ID is not provided or if no record is found.
* @example await User.findByIdAndDelete(1);
*/
static findByIdAndDelete(id: number): Promise<boolean>;
/**
* This static method updates a record in the table based on the provided ID.
* @param {number} id - The ID of the record to update.
* @param {object} data - The new data for the record.
* @example await Product.findByIdAndUpdate(1, { price: 200 });
* @returns {Promise<Model|null>} The updated instance or null if no record was found.
* @throws {Error} Throws an error if the ID is not provided or if no record is found.
*/
static findByIdAndUpdate(id: number, data: object): Promise<MappifyModel>;
}
/**
* This static method updates a record in the table based on the provided options.
* @param {object} options - The options for the query.
* @param {object} options.where - The WHERE clause for the query.
* @param {object} data - The new data for the record.
* @example await Product.findOneAndDelete({ where: { name: 'Product 1' } });
* @returns {Promise<Model|null>} The updated instance or null if no record was found.
* @throws {Error} Throws an error if the where clause is not provided or if no record is found.
*/
static findOneAndDelete(options: object): Promise<MappifyModel>;
/**
* This static method updates a record in the table based on the provided options.
* @param options The options for the query.
* @param options.where The WHERE clause for the query.
* @param options.attributes The columns to include in the result.
* @param options.exclude The columns to exclude from the result.
* @param data The new data for the record.
* @example await Product.findOneAndUpdate({ where: { id: 1 } }, { price: 200 });
* @returns The updated instance or null if no record was found.
* @throws Throws an error if the where clause is not provided or if no record is found.
*/
static findOneAndUpdate(options: { where?: object, attributes?: object, exclude?: object }, data: object): Promise<Model | null>;
/**
* Database class for managing MySQL connections.
* This static method updates a record in the table based on the provided ID.
* @param {number} id - The ID of the record to update.
* @param {object} data - The new data for the record.
* @example await Product.findByIdAndUpdate(1, { price: 200 });
* @returns {Promise<MappifyModel|null>} The updated instance or null if no record was found.
* @throws {Error} Throws an error if the ID is not provided or if no record is found.
*/
static findByIdAndUpdate(id: number, data: object): Promise<MappifyModel | null>;
}
/**
* Database class for managing MySQL connections.
* @example const db = new Database();
* db.createConnection().then((connection) => {
* console.log('Connection created successfully');
* } catch (err) {
* console.error(err);
* }
*/
export class Database {
/**
* Creates a new MySQL connection using the configuration.
* @example const db = new Database();
* db.createConnection().then((connection) => {
* console.log('Connection created successfully');
* } catch (err) {
* console.error(err);
* }
* @returns {Promise} A promise that resolves to the connection if successful, otherwise rejects with an error.
*/
createConnection(): Promise<any>;
/**
* Creates a new MySQL connection pool using the configuration.
* This method should be used when multiple connections are required.
* @example const db = new Database();
* db.createPool().then((pool) => {
* console.log('Pool created successfully');
* } catch (err) {
* console.error(err);
* }
* @returns {Promise} A promise that resolves to the connection pool if successful, otherwise rejects with an error.
*/
createPool(): Promise<any>;
/**
* Gets a promisified version of the query method from the connection.
* This method should be used to query the database.
* @example const db = new Database();
* db.createConnection().then((connection) => {
* console.log('Connection created successfully');
* const query = db.getQuery();
* query('SELECT * FROM users').then((results) => {
* console.log(results);
* } catch (err) {
* console.error(err);
* }
* @returns {Function} The promisified query method.
*/
export class Database {
/**
* Creates a new MySQL connection using the configuration.
* @example const db = new Database();
* db.createConnection().then((connection) => {
* console.log('Connection created successfully');
* } catch (err) {
* console.error(err);
* }
* @returns {Promise} A promise that resolves to the connection if successful, otherwise rejects with an error.
*/
createConnection(): Promise<any>;
getQuery(): Function;
/**
* Creates a new MySQL connection pool using the configuration.
* This method should be used when multiple connections are required.
* @example const db = new Database();
* db.createPool().then((pool) => {
* console.log('Pool created successfully');
* } catch (err) {
* console.error(err);
* }
* @returns {Promise} A promise that resolves to the connection pool if successful, otherwise rejects with an error.
*/
createPool(): Promise<any>;
/**
* Gets the current connection.
* @example const db = new Database();
* db.createConnection().then(() => {
* }).catch((err) => {
* console.log(err);
* });
* const connection = db.getConnection();
* @returns {Connection} The current connection
*/
getConnection(): Connection;
/**
* Gets a promisified version of the query method from the connection.
* This method should be used to query the database.
* @example const db = new Database();
* const query = db.getQuery();
* query('SELECT * FROM users').then((results) => {
* console.log(results);
* } catch (err) {
* console.error(err);
* }
* @returns {Function} The promisified query method.
*/
getQuery(): Function;
}
}
interface Connection {
/**
* Begins a transaction.
* @param {function} [callback] - Optional callback function.
*/
beginTransaction(callback?: (err: any) => void): void;
/**
* Commits the current transaction.
* @param {function} [callback] - Optional callback function.
*/
commit(callback?: (err: any) => void): void;
/**
* Rolls back the current transaction.
* @param {function} [callback] - Optional callback function.
*/
rollback(callback?: (err: any) => void): void;
/**
* Sends a SQL query to the database.
* @param {string} sql - The SQL query string.
* @param {any} [values] - Optional values for parameterized SQL queries.
* @param {function} [callback] - Optional callback function.
*/
query(sql: string, values?: any, callback?: (error: any, results: any, fields: any) => void): void;
/**
* Ends the connection.
* @param {function} [callback] - Optional callback function.
*/
end(callback?: (err: any) => void): void;
/**
* Destroys the connection.
*/
destroy(): void;
/**
* Pauses the connection.
*/
pause(): void;
/**
* Resumes the connection.
*/
resume(): void;
/**
* Escapes a value for SQL.
* @param {any} value - The value to escape.
* @returns {string} The escaped value.
*/
escape(value: any): string;
/**
* Escapes an identifier for SQL.
* @param {any} value - The identifier to escape.
* @returns {string} The escaped identifier.
*/
escapeId(value: any): string;
/**
* Formats a SQL query string.
* @param {string} sql - The SQL query string.
* @param {any} [values] - Optional values for parameterized SQL queries.
* @returns {string} The formatted SQL query string.
*/
format(sql: string, values?: any): string;
/**
* Pings the server.
* @param {function} [callback] - Optional callback function.
*/
ping(callback?: (err: any) => void): void;
/**
* Changes the user for the current connection.
* @param {any} options - The options for changing user.
* @param {function} [callback] - Optional callback function.
*/
changeUser(options: any, callback?: (err: any) => void): void;
}
}
const { Database } = require('./database');
const db = new Database();
db.createPool().then(() => {
db.createConnection().then(() => {
}).catch((err) => {

@@ -10,2 +10,2 @@ console.log(err);

module.exports = { query };
module.exports = { query };

@@ -29,2 +29,4 @@ const mysql = require('mysql2');

};
this.connection = this.createConnection() || this.createPool();
}

@@ -86,5 +88,6 @@

initializeConnection() {
this.query = util.promisify(this.connection.query).bind(this.connection);
this.connection.on('error', (err) => {
if (err.code === 'PROTOCOL_CONNECTION_LOST' || err.code === 'ECONNRESET') {
console.log('Database connection lost or reset. Reconnecting...');
console.log('Database connection lost. Reconnecting...');
if (this.connection.connect) {

@@ -97,4 +100,19 @@ this.connect();

});
}
/**
* Gets the current connection.
* @example const db = new Database();
* db.createConnection().then(() => {
* }).catch((err) => {
* console.log(err);
* });
* const connection = db.getConnection();
* @returns {any} The current connection.
*/
getConnection() {
return this.connection;
}
/**

@@ -101,0 +119,0 @@ * Gets a promisified version of the query method from the connection.

@@ -0,4 +1,26 @@

const { connection } = require('./connection');
const { Database } = require('./database');
const { MappifyModel } = require('./model');
// class User extends MappifyModel {
// }
// (async () => {
// try {
// connection.beginTransaction();
// let user = new User({ first_name: 'John', last_name: 'Doe' });
// await user.save();
// let user2 = new User({ firstname: 'Jane', last_name: 'Doe' });
// await user2.save();
// connection.commit();
// } catch (err) {
// connection.rollback();
// console.error(err);
// }
// })();
/**

@@ -5,0 +27,0 @@ * Database class for managing MySQL connections.

@@ -389,3 +389,3 @@ const { query } = require('../lib/connection');

* console.log(enrollment.course);
* @returns {this} The instance of the model with the populated relation.
* @returns {Promise<this>} A promise that resolves to the instance with the related data populated.
*/

@@ -460,2 +460,66 @@ async populate(relation, options = {}) {

/**
* This method attaches a new record to the related model and associates it with the current instance.
* @param {Model} target - The target model to attach.
* @param {string} relation - The record to attach to the relation.
* @param {object} options - The options for the query. - (optional)
* @param {Array} options.attributes - The columns to include in the result. - (optional)
* @param {Array} options.exclude - The columns to exclude from the result. - (optional)
* @example const user = await User.findById(1);
* const post = new Post({ title: 'Post 1', content: 'This is post 1' });
* await user.attach(post, 'posts');
* console.log(user);
* @example const order = await Order.findOne({ where: { id: 1 } });
* const shippingAddress = new ShippingAddress({ address: '123 Main St', city: 'Springfield', state: 'IL', zip: '62701' });
* await order.attach(shippingAddress, 'shippingAddress');
* console.log(order);
* @returns {Promise<this>} A promise that resolves to the instance with the related data attached.
* @throws {Error} Throws an error if the relation is not defined.
* @throws {Error} Throws an error if the relation is not a hasOne or hasMany relation.
* @throws {Error} Throws an error if the foreign key is not defined.
*/
async attach(target, relation, options = {}) {
if (!this.associations[relation]) {
throw new Error(`Relation "${relation}" is not defined`);
}
const relatedModel = this.associations[relation].model; // the related model
const foreignKey = this.associations[relation].foreignKey; // the foreign key in this model
if (this.associations[relation].type === 'hasMany') {
target[foreignKey] = this.id;
target.save();
this[relation] = await relatedModel.findAll({
where: { [foreignKey]: this.id }, // where the foreign key matches the id of this model
attributes: options?.attributes ? options?.attributes : ['*'], // select all columns by default
exclude: options?.exclude ? options?.exclude : [] // exclude no columns by default
}).then((result) => {
return result.map((item) => { // return the result as an array of objects
return Object.assign({}, item); // return the result as an object
});
}).catch((err) => {
console.log(err);
});
} else if (this.associations[relation].type === 'hasOne') {
target[foreignKey] = this.id;
target.save();
this[relation] = await relatedModel.findOne({
where: { [foreignKey]: this.id }, // where the foreign key matches the id of this model
attributes: options?.attributes ? options?.attributes : ['*'], // select all columns by default
exclude: options?.exclude ? options?.exclude : [] // exclude no columns by default
}).then((result) => {
return Object.assign({}, result); // return the result as an object
}).catch((err) => {
console.log(err);
});
} // if the relation is a hasOne relation
else {
throw new Error(`Relation "${relation}" is not a hasOne or hasMany relation`);
}
}
/**
* This method saves the instance to the database.

@@ -510,3 +574,3 @@ * @example const product = new Product({ name: 'Product 1', price: 100 });

* @example var products = await Product.fetch();
* @returns {Promise<Array<Model>>} An array of instances.
* @returns {Promise<Array<MappifyModel>>} An array of instances.
*/

@@ -610,3 +674,3 @@ static async fetch() {

* @example var products = await Product.findAll({ group: 'category' });
* @returns {Promise<Array<Model>>} An array of instances.
* @returns {Promise<Array<MappifyModel>>} An array of instances.
*/

@@ -620,3 +684,5 @@ static async findAll(options = {}) {

// Prepare WHERE clause
const { whereClause, whereValues } = prepareWhereClause(where, conditions);
if (Object.keys(where).length > 0) {
var { whereClause, whereValues } = prepareWhereClause(where, conditions);
}

@@ -636,6 +702,6 @@

// Construct SQL query
const sql = `SELECT ${selectedAttributes} FROM ${this.tableName} ${whereClause} ${groupClause} ${orderClause} ${limitClause} ${offsetClause}`;
console.log(sql, whereValues);
const sql = `SELECT ${selectedAttributes} FROM ${this.tableName} ${whereClause ? whereClause : ''} ${groupClause} ${orderClause} ${limitClause} ${offsetClause}`;
// Execute query
let result = await query(sql, whereValues);
let result = await query(sql, whereValues ? whereValues : []);
// Exclude unwanted attributes

@@ -698,3 +764,3 @@ result = result.map(row => {

* @example await Product.findOneAndDelete({ where: { name: 'Product 1' } });
* @returns {Promise<Model|null>} The updated instance or null if no record was found.
* @returns {Promise<MappifyModel|null>} The updated instance or null if no record was found.
* @throws {Error} Throws an error if the where clause is not provided or if no record is found.

@@ -722,3 +788,3 @@ */

* @example await Product.findOneAndUpdate({ where: { id: 1 } }, { price: 200 });
* @returns {Promise<Model|null>} The updated instance or null if no record was found.
* @returns {Promise<MappifyModel|null>} The updated instance or null if no record was found.
* @throws {Error} Throws an error if the where clause is not provided or if no record is found.

@@ -743,3 +809,3 @@ */

* @example await Product.findByIdAndUpdate(1, { price: 200 });
* @returns {Promise<Model|null>} The updated instance or null if no record was found.
* @returns {Promise<MappifyModel|null>} The updated instance or null if no record was found.
* @throws {Error} Throws an error if the ID is not provided or if no record is found.

@@ -746,0 +812,0 @@ */

{
"name": "mappifysql",
"version": "1.1.2",
"version": "1.1.3",
"description": "MappifySQL is a lightweight, easy-to-use Object-Relational Mapping (ORM) library for MySQL databases, designed for use with Node.js. It provides an intuitive, promise-based API for interacting with your MySQL database using JavaScript or TypeScript.",

@@ -5,0 +5,0 @@ "repository": {

@@ -1,6 +0,7 @@

# MappifySQL: A MySQL ORM for Node.js and TypeScript
<div align="center">
<img src="https://i.ibb.co/tmH8Kk4/mappifysql.jpg" alt="mappifysql" style="height: 300px; width: 300px; border-radius: 100%; object-fit: cover;">
</div>
MappifySQL is a lightweight, easy-to-use Object-Relational Mapping (ORM) library for MySQL databases, designed for use with Node.js. It provides an intuitive, promise-based API for interacting with your MySQL database using JavaScript or TypeScript.
---
---
<a href="https://www.npmjs.com/package/mappifysql"><img src="https://img.shields.io/npm/v/mappifysql.svg" alt="Version"></a>

@@ -11,2 +12,7 @@ <a href="https://www.npmjs.com/package/mappifysql"><img src="https://img.shields.io/npm/dt/mappifysql.svg" alt="Downloads"></a>

# MappifySQL: A MySQL ORM for Node.js and TypeScript
MappifySQL is a lightweight, easy-to-use Object-Relational Mapping (ORM) library for MySQL databases, designed for use with Node.js. It provides an intuitive, promise-based API for interacting with your MySQL database using JavaScript or TypeScript.
## Features

@@ -79,3 +85,3 @@

DB_PASSWORD=password
DB_DATABASE=mydatabase
DB_NAME=mydatabase
DB_PORT=3306 ## (optional) default is 3306

@@ -102,3 +108,3 @@ ```

var connection = db.connection;
var connection = db.getConnection();
var query = db.getQuery();

@@ -109,2 +115,5 @@

```
** Using TypeScript **
```typescript

@@ -122,3 +131,3 @@

var connection = db.connection;
var connection = db.getConnection();
var query = db.getQuery();

@@ -132,3 +141,3 @@

<div align="center">
<img src="https://i.ibb.co/BCvQSYL/create-Single-Connection.png" alt="createSingleConnection" border="0">
<img src="https://i.ibb.co/NptYQGf/createsingleconnection.png" alt="createSingleConnection" border="0">
</div>

@@ -151,3 +160,3 @@

var connection = db.connection;
var connection = db.getConnection();
var query = db.getQuery();

@@ -171,3 +180,3 @@

var connection = db.connection;
var connection = db.getConnection();
var query = db.getQuery();

@@ -179,8 +188,51 @@

<div align="center">
<img src="https://i.ibb.co/s3cnW5p/create-Pool-Connection.png" alt="createPoolConnection" border="0">
<img src="https://i.ibb.co/6r0npjy/createpoolconnection.png" alt="createPoolConnection" border="0">
</div>
Methods available in the connection object:
| Method | Description | Parameters | Supported by |
| --- | --- | --- | --- |
| `beginTransaction` | Begins a transaction. | `callback?: (err: any) => void` | `createConnection` |
| `commit` | Commits the current transaction. | `callback?: (err: any) => void` | `createConnection` |
| `rollback` | Rolls back the current transaction. | `callback?: (err: any) => void` | `createConnection` |
| `query` | Sends a SQL query to the database. | `sql: string`, `values?: any`, `callback?: (error: any, results: any, fields: any) => void` | `createConnection`, `createPool` |
| `end` | Ends the connection. | `callback?: (err: any) => void` | `createConnection`, `createPool` |
| `destroy` | Destroys the connection. | None | `createConnection` |
| `pause` | Pauses the connection. | None | `createConnection` |
| `resume` | Resumes the connection. | None | `createConnection` |
| `escape` | Escapes a value for SQL. | `value: any` | `createConnection`, `createPool` |
| `escapeId` | Escapes an identifier for SQL. | `value: any` | `createConnection`, `createPool` |
| `format` | Formats a SQL query string. | `sql: string`, `values?: any` | `createConnection`, `createPool` |
| `ping` | Pings the server. | `callback?: (err: any) => void` | `createConnection`, `createPool` |
| `changeUser` | Changes the user for the current connection. | `options: any`, `callback?: (err: any) => void` | `createConnection` |
Example:
```javascript
const { connection } = require('./connection');
connection.query('SELECT * FROM users', (err, results, fields) => {
if (err) {
throw err;
}
console.log('Fetched records:', results);
});
```
** Using TypeScript **
```typescript
import { connection } from './connection';
connection.query('SELECT * FROM users', (err, results, fields) => {
if (err) {
throw err;
}
console.log('Fetched records:', results);
});
```
### Using the Model Class

@@ -204,2 +256,4 @@

** Using TypeScript **
```typescript

@@ -209,56 +263,31 @@ import { MappifyModel } from 'mappifysql';

interface UserAttributes {
name: string;
id?: number;
first_name: string;
last_name: string;
email: string;
// add more properties here...
password: string;
//add more attributes here...
}
class User extends MappifyModel {
id: number;
name: string;
id?: number;
first_name: string;
last_name: string;
email: string;
// add more properties here...
password: string;
constructor(data: UserAttributes) {
super();
this.name = data.name;
this.id = data.id;
this.first_name = data.first_name;
this.last_name = data.last_name;
this.email = data.email;
// set more properties here...
}
this.password = data.password;
setProperties() {
super.setProperties();
// add more properties here...
}
async save() {
await super.save();
}
async update() {
await super.update();
}
async delete() {
await super.delete();
}
static async findAll() {
let results = await MappifyModel.findAll();
return results.map(result => new User(result));
}
static async findById(id: number){
let result = await MappifyModel.findById(id);
return new User(result);
}
static async findOne(options: { where: object }) {
let result = await MappifyModel.findOne(options);
return new User(result);
}
static async findOrCreate(options: object, defaults: object) {
let { record, created } = await MappifyModel.findOrCreate(options, defaults);
return { record: new User(record), created };
}
}

@@ -285,2 +314,4 @@

** Using TypeScript **
```typescript

@@ -354,2 +385,4 @@ import { MappifyModel } from 'mappifysql';

** Import in TypeScript **
```typescript

@@ -850,4 +883,8 @@ import User from 'path/to/user.ts'

try {
let results = await connection.query('SELECT * FROM products WHERE name LIKE ?', ['%apple%']);
console.log('Fetched records:', results);
let results = await connection.query('SELECT * FROM products WHERE name LIKE ?', ['%apple%'], (err, results, fields) => {
if (err) {
throw err;
}
console.log('Fetched records:', results);
});
} catch (err) {

@@ -919,2 +956,4 @@ console.error(err);

** Using TypeScript **
```typescript

@@ -924,2 +963,3 @@ const { MappifyModel } = require('mappifysql');

interface ProductAttributes {
id?: number;
name: string;

@@ -931,3 +971,3 @@ price: number;

class Product extends MappifyModel {
id: number;
id?: number;
name: string;

@@ -939,2 +979,3 @@ price: number;

super();
this.id = data.id;
this.name = data.name;

@@ -945,3 +986,2 @@ this.price = data.price;

// other methods here...

@@ -979,2 +1019,4 @@ // create a custom function using functions in the model class

<span style="color:red;"><b>Note</b></span>: Transactions are only supported when created a single connection using the createConnection method. Transactions are not supported in pool because a pool consists of multiple connections to the database.
```javascript

@@ -985,12 +1027,9 @@ const { connection, query } = require('./connection');

try {
await connection.beginTransaction();
connection.beginTransaction();
var user = await query('INSERT INTO users SET ?', { name: 'John Doe'});
await query('INSERT INTO addresses SET ?', { user_id: user.insertId, address: '123 Main St' });
await connection.commit();
connection.commit();
console.log('Transaction completed successfully');
query('SELECT * FROM users').then((results) => {
console.log('Fetched records:', results);
});
} catch (err) {
await connection.rollback();
connection.rollback();
console.error(err);

@@ -1004,3 +1043,3 @@ }

try {
await connection.beginTransaction();
connection.beginTransaction();
let user = new User({ name: 'John Doe' });

@@ -1010,7 +1049,4 @@ await user.save();

await address.save();
await connection.commit();
connection.commit();
console.log('Transaction completed successfully');
User.findAll().then((results) => {
console.log('Fetched records:', results);
});
} catch (err) {

@@ -1039,2 +1075,3 @@ await connection.rollback();

| `populate` | Fetches the related data for a given relation. | `relation`, `options` (optional) | `await post.populate('user');` |
| `attach` | Attaches a new record to the related model and associates it with the current model. | `target`, `relation`, `options` (optional) | `await post.attach(post, 'posts');` |

@@ -1059,7 +1096,15 @@

| | otherKey | The foreign key in through model for the related model. |
| populate | attributes | The columns to include in the result. |
| populate | relation | The name of the relation to fetch. |
| | attributes | The columns to include in the result. |
| | exclude | The columns to exclude from the result. |
| attach | target | The record to attach to the related model. |
| | relation | The name of the relation to attach to. |
| | attributes | The columns to include in the result. |
| | exclude | The columns to exclude from the result. |
Please note that `attributes` and `exclude` keys in the `populate` method are optional.
Please note that `attributes` and `exclude` keys in the `populate` and `attach` methods are optional and can be used to specify the columns to include or exclude from the result.
<span style="color:red;"><b>Note</b></span>: The `populate` method is used to fetch the related data for a given relation. The `attach` method is used to attach a new record to the related model and associate it with the current model and it can only be used with the `hasOne` and `hasMany` relationships.
#### Defining Relationships

@@ -1093,4 +1138,4 @@

Order.findByOne({ where: { id: 1 }}).then((order) => {
order.populate('shippingAddress', {exclude: ['created_at', 'updated_at']}).then((order) => {
Order.findByOne({ where: { id: 1 }}).then(async (order) => {
await order.populate('shippingAddress', {exclude: ['created_at', 'updated_at']}).then((order) => {
console.log('Order with shipping address:', order);

@@ -1102,2 +1147,12 @@ });

Order.findAll().then(async (orders) => {
await Promise.all(orders.map(async (order) => {
await order.populate('shippingAddress', {exclude: ['created_at', 'updated_at']});
}));
console.log('Orders with shipping addresses:', orders);
}).catch((err) => {
console.error(err);
});
```

@@ -1110,3 +1165,3 @@

interface ShippingAddressAttributes {
id: number;
id?: number;
address: string;

@@ -1118,3 +1173,3 @@ city: string;

class ShippingAddress extends MappifyModel {
id: number;
id?: number;
address: string;

@@ -1130,6 +1185,5 @@ city: string;

// other methods here...
super.associations() {
super.belongsTo(Order, {
associations() {
this.belongsTo(Order, {
as: 'order',

@@ -1149,4 +1203,4 @@ key: 'id'

ShippingAddress.findByOne({ where: { id: 1 }}).then((shippingAddress) => {
shippingAddress.populate('order', {attributes: ['id', 'total']}).then((shippingAddress) => {
ShippingAddress.findByOne({ where: { id: 1 }}).then(async(shippingAddress) => {
await shippingAddress.populate('order', {attributes: ['id', 'total']}).then((shippingAddress) => {
console.log('Shipping address with order:', shippingAddress);

@@ -1158,4 +1212,45 @@ });

ShippingAddress.findAll().then(async (shippingAddresses) => {
await Promise.all(shippingAddresses.map(async (shippingAddress) => {
await shippingAddress.populate('order', {attributes: ['id', 'total']});
}));
console.log('Shipping addresses with orders:', shippingAddresses);
}).catch((err) => {
console.error(err);
});
```
** Using `attach` method **
```javascript
const Order = require('path/to/Order');
const ShippingAddress = require('path/to/ShippingAddress');
let createShippingAddress = async () => {
var order = await Order.findById(1);
var shippingAddress = new ShippingAddress({ address: '123 Main St', city: 'New York', state: 'NY' });
await order.attach(shippingAddress, 'shippingAddress', { exclude: ['created_at', 'updated_at'] });
console.log('Shipping address created:', shippingAddress);
};
createShippingAddress();
```
```typescript
import Order from 'path/to/Order';
import ShippingAddress from 'path/to/ShippingAddress';
let createShippingAddress = async () => {
var order = await Order.findOne({ where: { id: 1 } });
var shippingAddress = new ShippingAddress({ address: '123 Main St', city: 'New York', state: 'NY' });
await order.attach(shippingAddress, 'shippingAddress');
console.log('Shipping address created:', shippingAddress);
};
createShippingAddress();
```
#### One-to-Many Relationship

@@ -1202,3 +1297,3 @@

interface OrderAttributes {
id: number;
id?: number;
total: number;

@@ -1209,3 +1304,3 @@ }

class Order extends MappifyModel {
id: number;
id?: number;
total: number;

@@ -1219,6 +1314,5 @@

// other methods here...
super.associations() {
super.belongsTo(User, {
associations() {
this.belongsTo(User, {
as: 'user',

@@ -1249,2 +1343,35 @@ key: 'id'

** Using `attach` method **
```javascript
const User = require('path/to/User');
const Order = require('path/to/Order');
let createOrder = async () => {
var user = await User.findById(1);
var order = new Order({ total: 1000 });
await user.attach(order, 'orders');
console.log('Order created:', order);
};
createOrder();
```
```typescript
import User from 'path/to/User';
import Order from 'path/to/Order';
let createOrder = async () => {
var user = await User.findOne({ where: { id: 1 } });
var order = new Order({ total: 1000 });
await user.attach(order, 'orders');
console.log('Order created:', order);
};
createOrder();
```
#### Many-to-Many Relationship

@@ -1274,3 +1401,2 @@

```
Usage:

@@ -1290,2 +1416,4 @@ ```javascript

** Using TypeScript **
```typescript

@@ -1297,3 +1425,3 @@ import { MappifyModel } from 'mappifysql';

interface CategoryAttributes {
id: number;
id?: number;
name: string;

@@ -1303,3 +1431,3 @@ }

class Category extends MappifyModel {
id: number;
id?: number;
name: string;

@@ -1313,6 +1441,6 @@

// other methods here...
super.associations() {
super.belongsToMany(Product, {
associations() {
this.belongsToMany(Product, {
as: 'products',

@@ -1395,3 +1523,3 @@ through: ProductCategory,

interface EnrollmentAttributes {
id: number;
id?: number;
student_id: number;

@@ -1402,3 +1530,3 @@ course_id: number;

class Enrollment extends MappifyModel {
id: number;
id?: number;
student_id: number;

@@ -1414,6 +1542,5 @@ course_id: number;

// other methods here...
super.associations() {
super.belongsTo(Student, {
associations() {
this.belongsTo(Student, {
as: 'student',

@@ -1423,3 +1550,3 @@ key: 'id',

});
super.belongsTo(Course, {
this.belongsTo(Course, {
as: 'course',

@@ -1484,1 +1611,4 @@ key: 'id',

<!-- - [MappifySQL Open Source Community]( -->
<a href="https://www.buymeacoffee.com/walidadebayo"><img src="https://img.buymeacoffee.com/button-api/?text=Buy me a coffee&emoji=&slug=walidadebayo&button_colour=FFDD00&font_colour=000000&font_family=Comic&outline_colour=000000&coffee_colour=ffffff" /></a>
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc