![Oracle Drags Its Feet in the JavaScript Trademark Dispute](https://cdn.sanity.io/images/cgdhsj6q/production/919c3b22c24f93884c548d60cbb338e819ff2435-1024x1024.webp?w=400&fit=max&auto=format)
Security News
Oracle Drags Its Feet in the JavaScript Trademark Dispute
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
kp-mysql-models
Advanced tools
`kp-mysql-models` is a lightweight, easy-to-use, and promise-based Node.js ORM tool designed for MySQL. It simplifies database interactions by offering features like model-based query building, CRUD operations, and support for advanced queries such as joi
The
kp-mysql-models
is a mysql query builder light weight library that simplifies interactions with MySQL databases and it's promise-based Node.js ORM tool. It streamlines tasks such as creating, inserting, updating, and deleting records, and handles complex operations like joins, pagination, and conditionals. Its intuitive and efficient approach can greatly expedite development, saving both time and effort.
npm i kp-mysql-models
const { BaseModels } = require("kp-mysql-models");
npm i @krishnapawar/kp-mysql-models
const { BaseModels } = require("@krishnapawar/kp-mysql-models");
hasOne
, belongsTo
, hasMany
.Ensure you have a MySQL connection set up using the mysql
library:
const mysql = require("mysql");
const pool = mysql.createPool({
connectionLimit: 10,
host: "localhost",
user: "root",
password: "",
database: "test",
});
Create a model for the users
table:
const { BaseModels } = require("@krishnapawar/kp-mysql-models");
const User = new BaseModels({
_table: "users",
_connection: pool,
});
Create model classes by extending BaseModels
for better organization and customization:
1 Define the User Class: Extend BaseModels to create a model for the users table. 2 Initialize Connection: Use the super() method to pass the database connection (e.g., pool) to the BaseModels class. 3 Export the Model: Export User to make it accessible across the project.
// suppose tabet name is uses than create file User.js write code like this and use it in controller
const { BaseModels } = require("@krishnapawar/kp-mysql-models");
const { pool } = require("./db"); // Import the pool connection
class User extends BaseModels {
constructor() {
super(pool); // Connect to the database using super()
}
}
module.exports = User;
// This code snippet imports necessary modules, defines the User class that extends BaseModels, and connects to the database using the super() method, following the given guidelines.
const { BaseModels } = require("@krishnapawar/kp-mysql-models");
class User extends BaseModels {
constructor() {
super(pool);
this._table = "users";
}
}
module.exports = User;
We can customize other model settings such as soft delete, hidden fields, and fields to show. Here's how you can implement this:
const { BaseModels } = require("@krishnapawar/kp-mysql-models");
const { pool } = require("./db");
class User extends BaseModels {
constructor() {
super();
// Manually set the table name and database connection if not automatically connected
this._table = "users";
this._connection = pool;
// Additional model settings
this._softDelete = false; // Disable soft delete functionality
this._hidden = ['password']; // Fields to hide from query results
this._show = ['id', 'name', 'email']; // Fields to show in query results
}
}
module.exports = User;
Note:-
This code snippet ensures that the table name (users), the database connection (pool) and other settings are explicitly set within the User class constructor
if they are not automatically handled.
// Get the first user
const firstUser = await User.first();
// Fetch all users
const users = await User.get();
// Filtered query
const filteredUsers = await User.where({ role: "admin" }).get();
// Insert new record
await User.create({ name: "John Doe", email: "john@example.com" });
// Update a record
await User.where({ id: 1 }).update({ name: "John Smith" });
// Delete a record
await User.where({ id: 1 }).delete();
// Paginate results (10 records per page)
const page = await User.pagination({ currentPage: 2, perPage: 10 }).get();
// Soft delete a record
await User.where({ id: 1 }).trashed();
// Restore a soft-deleted record
await User.where({ id: 1 }).restore();
// Fetch only soft-deleted records
const deletedUsers = await User.onlyTrashed().get();
// Fetch only active records
const activedUsers = await User.withoutTrashed().get();
// Soft delete all records
let data = await user.trashedAll();
// Soft restore all records
let data = await user.restoreAll();
// Soft clear trash records
let data = await user.clearTrash();
// Truncate the table
let data = await User.truncate();
//delete record
let data = await user.deleleAll();
//delete record
let data = await user.destroy({
where: {
id: 585,
}
});
//find first record by id
let data = await User.findOne(13);
The updateOrCreate method updates data if the record exists, or inserts new data if it doesn’t. Specify the fields to update or insert in elements, and conditions in where.
const dataj = await User.updateOrCreate({
elements: {
first_name: "ram",
last_name: "ji",
},
where: {
id: 1223,
}
});
The save method can both insert and update records. If a where condition is provided, it updates matching records; otherwise, it creates a new entry.
const dataj = await User.save({
elements: {
first_name: "ram",
last_name: "ji",
},
// where: {
// id: 1223,
// },
});
let data = await User.findOneById(13);
let data = await User.find({
id:12,
name:"test",
date:"12/10/2023"
});
The with() method in kp mysql model allows you to establish and query relational data within your models, supporting relationships like hasOne
, belongsTo
, hasMany
, and connect
. This method lets you fetch related data alongside the main record in a structured way, and you can even build multi-level relationships for nested data retrieval.
Note:-
belongsTo
and hasOne
give single response with single object data and other hand hasMany
and connect
, give array object response with multiple object data `.
class User extends BaseModel {
constructor() {
super(pool);
}
// Example 1: Define Relationships
business(){
return this.hasOne('businesses',{'user_id':'id'});
}
// Example 2: Define Relationships
orders(){
return this.hasMany('orders',{'business_id':'business_id'},async()=>{
return {
where:{
order_status:"pending"
}
}
});
}
// Example 3: Define Relationships
order_items(){
return this.hasMany('order_items',{'order_id':'order_id'},{
where:{
status:"pending"
}
});
}
// Example 4: Define Relationships
menu_item(){
return this.belongsTo('menu_items',{'menu_item_id':'menu_item_id'});
}
//set all relation method in init
init(){
return[
this.orders(),
this.business(),
this.menu_item(),
this.order_items()
]
}
}
export default new User;
let data = await User.where('id',1).with('business').get();
//output
=>[
{
"id": 1,
"name": "krish",
"email": "krish@test.com",
"password": "1weqweq",
"role": "staff",
"phone": null,
"created_at": "2024-12-20T19:36:05.000Z",
"updated_at": "2024-12-20T19:36:05.000Z",
"business": {
"business_id": 1,
"user_id": 1,
"name": "The Gourmet Kitchen",
"address": "123 Flavor Street, Food City",
"phone": "123-456-7890",
"email": "contact@gourmetkitchen.com",
"created_at": "2024-11-01T16:58:28.000Z",
"updated_at": "2024-12-20T19:37:03.000Z"
}
}
]
let data = await User.where('id',1).with('business',{where:{"business_id": 2}}).get();
//output
=>[
{
"id": 1,
"name": "krish",
"email": "krish@test.com",
"password": "1weqweq",
"role": "staff",
"phone": null,
"created_at": "2024-12-20T19:36:05.000Z",
"updated_at": "2024-12-20T19:36:05.000Z",
"business": {}
}
]
Retrieve data from multiple nested tables
// example 3
let data = await User.where('id',1).with({
'business':(q)=>q.setWith({
"orders":(q)=>q.setWith({
'order_items':(q)=>q.setWith('menu_item')
})
})
}).get();
// example 4 adding condition in with method
let data = await User.where('id',1).with({
'business':(q)=>q.setWith({
"orders":(q)=>q.setWith({
'order_items':(q)=>q.setWith('menu_item')
},{
where:{
"order_id": 1
}
})
})
}).get();
// example 5 adding complex raletion in easy way using with method
let data = await User.where('id',1).with({
'business':(q)=>q.setWith({
"orders":(q)=>q.setWith({
'order_items':(q)=>q.setWith('menu_item')
},{
where:{
"order_id": 1
}
})
})
}).with('menu_item',{where:{id:1}}).get();
Note:- the key same as relation method name that we write in model
const data = await user.first({
select: [
"id",
"first_name",
"last_name"
],
with: {
doctor: {
table: "appointments",
limit: 2,
select: ["id", "user_id"],
hasMany: {
user_id: "id",
},
}
},
where: {
id: 585,
},
});
hasOne
, belognsTo
, hasMany
, connect
in (with:{}).const data = await user.get({
select: ["id", "created_by_id", "first_name", "last_name"],
with: {
doctor: {
table: "appointments",
limit: 2,
select: ["id", "user_id"],
connect: {
user_id: "id",
},
},
clinic: {
table: "appointments",
limit: 2,
where:{
role_id="5"
},
select: ["id", "user_id"],
hasMany: {
doctor_id: "id",
},
},
},
where: {
created_by_id: "1",
},
});
The dbJoin() method in kp mysql model enables complex joins for enhanced querying. With options like join, innerJoin, leftJoin, and rightJoin, as well as pagination and sorting, it simplifies fetching related data across tables.
let data = await user
.select("users.id as uId,appointments.id,users.first_name,lab.first_name as lab_name")
.join('appointments',"users.id", "appointments.patient_id")
.innerJoin("users lab","lab.id", "appointments.user_id")
.leftJoin("users lab1","lab1.id", "appointments.user_id")
.rightJoin("users lab2","lab2.id", "appointments.user_id")
.where({
"users.id": 1122,
})
.when(true,(q)=>{
return q.where("appointments.id",1489);
})
.pagination({currentPage:1,perPage:20})
.latest("appointments.id")
.dbJoin();
//or we co using config object for example
const data = await user.dbJoin({
table: "users",
limit: 10,
select: [
"users.id as uId",
"appointments.id",
"users.first_name",
"lab.first_name as lab_name",
],
latest: "appointments.id",
join: [
{
type: "hasOne",
table: "appointments",
on: {
"users.id": "appointments.patient_id",
},
},
{
type: "belongsTo",
table: "users lab",
on: {
"lab.id": "appointments.user_id",
},
},
],
where: {
"users.id": 1122,
},
pagination: page,
});
you can also use for this method to join mutlipal table
const data = await user.dbWith({
table: "users",
limit: 10,
select: [
"users.id as uId",
"appointments.id",
"users.first_name",
"lab.first_name as lab_name",
],
latest: "appointments.id",
with: {
hasOne: [
{
table: "appointments",
on: {
"users.id": "appointments.patient_id",
},
},
{
table: "users clinic",
on: {
"clinic.id": "appointments.clinic_id",
},
},
],
belongsTo: [
{
table: "users lab",
on: {
"lab.id": "appointments.user_id",
},
},
],
},
where: {
"users.id": 1122,
},
pagination: page,
});
Note:- we can use left join
, right join
, join
and inner join
instant of hasOne
, belognsTo
, hasMany
, connect
in dbJoin()
,dbWith()
and also with with
.
import all Helper method Example
const {
setDBConnection,
get,
first,
save,
create,
update,
dbJoin,
dbWith,
} = require("kp-mysql-models");
first you have to setup mysql connection for using helper. we can setup by using setBDConnection() method to connect database or we can directly pass mysql pool or db connection object or params in help method look both example in below.
var mysql = require("mysql");
var pool = mysql.createPool({
connectionLimit: 10,
host: "localhost",
user: "root",
password: "",
database: "test",
});
Example 1 for using setDBConnection method
setDBConnection(pool);
const data = await get({
table: "users",
whereNotIn: {
id: [1, 1221],
}
});
You can also pass the connection object to each method directly Example 2 for directly pass db connection
const data = await get({
table: "users",
whereNotIn: {
id: [1, 1221],
}
},pool);
Available important Helper methods can we use as well
create method using for create data
const data = await create({
table: "users",
elements: {
first_name: "ram",
last_name: "ji",
}
});
update method using for updating data
const dataj = await update({
table: "users",
elements: {
first_name: "ram",
last_name: "ji",
},
where: {
id: 1223,
}
});
save method using for create or updating data
const dataj = await save({
table: "users",
elements: {
first_name: "ram",
last_name: "ji",
},
// where: {
// id: 1223,
// },
});
get()
: Fetch multiple records.first()
: Fetch the first record.find()
: Retrieve records by conditions.findOne()
: Retrieve single records by conditions.findOneByEmail()
: Fetch a record by its Email.findOneById()
: Fetch a record by its ID.where()
: Apply conditions to filter results.whereOr()
: Apply OR conditions.whereIn()
: Filter records where a column value matches an array.whereNotIn()
: Exclude records where a column value matches an array.whereNull()
: Filter records where a column value is NULL
.whereNotNull()
: Filter records where a column value is not NULL
.whereRaw()
: Apply raw SQL conditions.onlyTrashed()
: Fetch only soft-deleted records.exists()
: Check if a record exists based on conditions.pagination()
: Implement dynamic pagination.join()
: Add basic join clauses.leftJoin()
: Add left join clauses.rightJoin()
: Add right join clauses.innerJoin()
: Add inner join clauses.create()
: Insert new records into the database.update()
: Update existing records.delete()
: Delete records based on conditions.truncate()
: Remove all records from a table.updateOrCreate()
: Update records if they exist or insert them if they don’t.save()
: Create or update records based on conditions.destroy()
: Delete records (supports soft delete).restore()
: Restore soft-deleted records.trashed()
: Soft delete a record.trashedAll()
: Soft delete all records.restoreAll()
: Restore all soft-deleted records.clearTrash()
: delete permanent trashed records.hasOne()
: Define a one-to-one relationship.hasMany()
: Define a one-to-many relationship.belongsTo()
: Define an inverse one-to-one or many-to-one relationship.connect()
: Define a custom connection between tables.Keyword | Description |
---|---|
table | Specifies the database table |
select | Columns to retrieve |
where | Apply conditions |
join | Define table relationships |
onlyTrashed | Fetch only soft-deleted records |
pagination | Define pagination settings |
hasOne | Define a one-to-one relationship |
hasMany | Define a one-to-many relationship |
groupBy | Groups records based on specified columns |
raw | Add raw SQL expressions |
table(x)
query.table('users')
select(x)
query.select(['id', 'name'])
latest(x)
query.latest('created_at')
limit(x)
query.limit(10)
groupBy(x)
query.groupBy('status')
raw(x)
query.raw('COUNT(*)')
having(x)
HAVING
clause.query.having('COUNT(id) > 10')
onlyTrashed()
query.onlyTrashed()
when(c, cb)
query.when(userIsAdmin, q => q.where('role', 'admin'))
where(c, v=false)
WHERE
clause with specified conditions.query.where('status', 'active')
whereOr(c, v=false)
OR WHERE
clause.query.whereOr('role', 'user')
whereIn(column, values)
query.whereIn('id', [1, 2, 3])
whereNotIn(column, values)
query.whereNotIn('status', ['inactive', 'deleted'])
whereNull(column)
NULL
.query.whereNull('deleted_at')
whereNotNull(column)
NULL
.query.whereNotNull('created_at')
whereRaw(c)
WHERE
clause.query.whereRaw('age > 18')
with(c)
with
).query.with({ posts: { ... } })
pagination(x)
currentPage
and perPage
limit.query.pagination({ currentPage: 1, perPage: 20 })
rightJoin(x, y, z, cb=false)
RIGHT JOIN
clause.query.rightJoin('comments', 'users.id', 'comments.user_id')
innerJoin(x, y, z, cb=false)
INNER JOIN
clause.query.innerJoin('posts', 'users.id', 'posts.user_id')
join(x, y, z, cb=false)
JOIN
clause.query.join('orders', 'users.id', 'orders.user_id')
leftJoin(x, y, z, cb=false)
LEFT JOIN
clause.query.leftJoin('profile', 'users.id', 'profile.user_id')
buildQuery(d=false)
x
) if d
is true
, or the QueryBuilder
instance itself for chaining.table:
select:
elements:
latest:
limit:
pagination:
with:
connect:
hasOne:
belongsTo:
hasMany:
join:
dbWith:
where:
whereOr, whereIn, whereNotIn, whereIs, whereIsNull, whereIsNotNull, whereRaw:
on, onOr, onIn, onNotIn, onIs, onRaw:
onlyTrashed:
groupBy:
where
and on
operations with exampleswhere:-
where: {
id: 1223,
}
whereOr:-
whereOr: {
id: 1223,
}
whereIn:-
whereIn: {
id: [1, 1221],
}
whereNotIn:-
whereNotIn: {
id: [1, 1221],
}
whereIs:-
whereIs: {
last_name: "NULL",
}
whereIsNot:-
whereIsNot: {
last_name: "NULL",
}
whereRaw:-
whereRaw:"name='mohan' and age=30 "
on:-
on: {
id: 1223,
}
onOr:-
onOr: {
id: 1223,
}
onIn:-
onIn: {
id: [1, 1221],
}
onNotIn:-
onNotIn: {
id: [1, 1221],
}
onIs:-
onIs: {
last_name: "NULL",
}
onIsNot:-
onIsNot: {
last_name: "NULL",
}
onRaw:-
onRaw:"name='mohan' and age=30 "
const users = [
{ id: 1, name: 'John Doe', age: 30, contact: { address: 'test', phone: 90876543 } },
{ id: 2, name: 'Jane Doe', age: 25, contact: { address: 'test1', phone: 908765431 } },
{ id: 3, name: 'Mary Jane', age: 35, contact: { address: 'test2', phone: 908765432 } },
{ id: 4, name: 'Peter Parker', age: 28 },
{ id: 5, name: 'Bruce Wayne', age: 32 },
];
const collection = collect(users);
console.log(collection.where('name', '=', 'John Doe').where('age', '<', 40).first());
//{ id: 1, name: 'John Doe', age: 30, contact: { address: 'test', phone: 90876543 } }
console.log(collection.whereOr(['name', '=', 'John Doe'], ['age', '<', 30]).toArray());
// [
// { id: 1, name: 'John Doe', age: 30, contact: { address: 'test', phone: 90876543 } },
// { id: 2, name: 'Jane Doe', age: 25, contact: { address: 'test1', phone: 908765431 } },
// { id: 4, name: 'Peter Parker', age: 28 },
// ]
console.log(collection.whereIn('name', ['John Doe', 'Jane Doe']).toArray());
// [
// { id: 1, name: 'John Doe', age: 30, contact: { address: 'test', phone: 90876543 } },
// { id: 2, name: 'Jane Doe', age: 25, contact: { address: 'test1', phone: 908765431 } },
// ]
console.log(collection.whereNotIn('name', ['John Doe', 'Jane Doe']).toArray());
// [
// { id: 3, name: 'Mary Jane', age: 35, contact: { address: 'test2', phone: 908765432 } },
// { id: 4, name: 'Peter Parker', age: 28 },
// { id: 5, name: 'Bruce Wayne', age: 32 },
// ]
console.log(collection.whereNull('nickname').toArray());
// [
// { id: 1, name: 'John Doe', age: 30, contact: { address: 'test', phone: 90876543 } },
// { id: 2, name: 'Jane Doe', age: 25, contact: { address: 'test1', phone: 908765431 } },
// { id: 3, name: 'Mary Jane', age: 35, contact: { address: 'test2', phone: 908765432 } },
// { id: 4, name: 'Peter Parker', age: 28 },
// { id: 5, name: 'Bruce Wayne', age: 32 },
// ]
console.log(collection.whereNotNull('name').toArray());
// [
// { id: 1, name: 'John Doe', age: 30, contact: { address: 'test', phone: 90876543 } },
// { id: 2, name: 'Jane Doe', age: 25, contact: { address: 'test1', phone: 908765431 } },
// { id: 3, name: 'Mary Jane', age: 35, contact: { address: 'test2', phone: 908765432 } },
// { id: 4, name: 'Peter Parker', age: 28 },
// { id: 5, name: 'Bruce Wayne', age: 32 },
// ]
console.log(collection.pluck('contact').toArray());
// [
// { address: 'test', phone: 90876543 },
// { address: 'test1', phone: 908765431 },
// { address: 'test2', phone: 908765432 },
// undefined,
// undefined,
// ]
console.log(collection.pluckDeep('contact.phone').toArray());
// [90876543, 908765431, 908765432, undefined, undefined]
console.log(collection.where('contact.phone', '>', 908765430).toArray());
// [{ id: 2, ...}, { id: 3, ...}]
console.log(collection.whereOr(['contact.phone', '=', 90876543], ['contact.address', '=', 'test1']).toArray());
// [{ id: 1, ...}, { id: 2, ...}]
console.log(collection.whereIn('contact.address', ['test', 'test1']).toArray());
// [{ id: 1, ...}, { id: 2, ...}]
console.log(collection.whereNotIn('contact.address', ['test', 'test1']).toArray());
// [{ id: 3, ...}, { id: 4, ...}, { id: 5, ...}]
console.log(collection.whereNull('contact.phone').toArray());
// [{ id: 4, ...}, { id: 5, ...}]
console.log(collection.whereNotNull('contact.phone').toArray());
// [{ id: 1, ...}, { id: 2, ...}, { id: 3, ...}]
console.log(collection.pluck('contact.phone').toArray());
//[90876543, 908765431, 908765432, null, null]
//you can use in chaining as well example
console.log(collection.where('name', '=', 'John Doe').where('age', '<', 40).first());
// Get the first item
const firstUser = collection.first();
// { id: 1, name: 'John Doe', age: 30 }
// Get the last item
const lastUser = collection.last();
// { id: 5, name: 'Bruce Wayne', age: 32 }
// Check if a value exists in the collection
const containsJohnDoe = collection.contains(users[0]);
// true
// Get unique items
const uniqueAges = collection.pluck('age').unique();
// [30, 25, 35, 28, 32]
// Get the count of items
const count = collection.count();
// 5
// Check if the collection is empty
const isEmpty = collection.isEmpty();
// false
// Convert collection to plain array
const array = collection.toArray();
// same as users
// Chunk the collection into arrays of 2 items each
const chunked = collection.chunk(2);
// [
// [{ id: 1, name: 'John Doe', age: 30 }, { id: 2, name: 'Jane Doe', age: 25 }],
// [{ id: 3, name: 'Mary Jane', age: 35 }, { id: 4, name: 'Peter Parker', age: 28 }],
// [{ id: 5, name: 'Bruce Wayne', age: 32 }]
// ]
// Order by age in ascending order
const orderedByAgeAsc = collection.orderBy('age');
// [
// { id: 2, name: 'Jane Doe', age: 25 },
// { id: 4, name: 'Peter Parker', age: 28 },
// { id: 1, name: 'John Doe', age: 30 },
// { id: 5, name: 'Bruce Wayne', age: 32 },
// { id: 3, name: 'Mary Jane', age: 35 }
// ]
// Order by age in descending order
const orderedByAgeDesc = collection.orderBy('age', 'desc');
// [
// { id: 3, name: 'Mary Jane', age: 35 },
// { id: 5, name: 'Bruce Wayne', age: 32 },
// { id: 1, name: 'John Doe', age: 30 },
// { id: 4, name: 'Peter Parker', age: 28 },
// { id: 2, name: 'Jane Doe', age: 25 }
// ]
const totalAge = collection.sum('age'); // 90
const averageAge = collection.avg('age'); // 30
const groupedByAge = collection.groupBy('age');
// {
// 30: [{ id: 1, name: 'John Doe', age: 30 }],
// 25: [{ id: 2, name: 'Jane Doe', age: 25 }],
// 35: [{ id: 3, name: 'Mary Jane', age: 35 }]
// }
//data sort
const sortedByName = collection.sortBy('name')
const phone = collection.values('contact.phone') // [90876543, 908765431, 908765432, undefined, undefined]
const keys = collection.keys().toArray() // ['id', 'name', 'age', 'contact']
// Remove specified keys from the collection
const withoutAge = collect(users).except(['age']).toArray();
// [
// { id: 1, name: 'John Doe' },
// { id: 2, name: 'Jane Doe' },
// { id: 3, name: 'Mary Jane' }
// ]
// Only include specified keys in the collection
const onlyName = collect(users).only(['name']).toArray();
// [
// { name: 'John Doe' },
// { name: 'Jane Doe' },
// { name: 'Mary Jane' }
// ]
// Key the collection by the specified key
const keyedById = collect(users).keyBy('id').toArray();
// {
// 1: { id: 1, name: 'John Doe', age: 30 },
// 2: { id: 2, name: 'Jane Doe', age: 25 },
// 3: { id: 3, name: 'Mary Jane', age: 35 }
// }
// Execute a callback on the collection
const tapped = collect(users).tap(collection => console.log(collection.count())).toArray();
// Logs: 3
// [
// { id: 1, name: 'John Doe', age: 30 },
// { id: 2, name: 'Jane Doe', age: 25 },
// { id: 3, name: 'Mary Jane', age: 35 }
// ]
*Let's see more examples
const items = [1, [2, 3], [[4, 5]], [[[6]]]];
const collection = collect(items);
// Flatten the multi-dimensional array
const flattened = collection.flatten().toArray();
// [1, 2, 3, 4, 5, 6]
// Flatten the array to a depth of 1
const flat1 = collection.flat();
// [1, 2, 3, [4, 5], [[6]]]
// Flatten the array to a depth of 2
const flat2 = collection.flat(2);
// [1, 2, 3, 4, 5, [6]]
// Flatten the array completely
const flatInfinity = collection.flat(Infinity);
// [1, 2, 3, 4, 5, 6]
// Get items that are present in both collections
const intersected = collect([1, 2, 3]).intersect([2, 3, 4]).toArray();
// [2, 3]
// Get items that are in the first collection but not in the second
const diff = collect([1, 2, 3]).diff([2, 3, 4]).toArray();
// [1]
const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const collection = collect(items);
// Paginate the collection with 3 items per page, and get page 2
const paginated = collection.paginate(3, 2);
console.log(paginated);
// {
// data: Collection { items: [ 4, 5, 6 ] },
// currentPage: 2,
// perPage: 3,
// totalItems: 10,
// totalPages: 4,
// from: 4,
// to: 6
// }
// Get the paginated data
const pageData = paginated.data.toArray();
// [4, 5, 6]
const numbers = [1, 2, 3, 4, 5, 6];
const collection = collect(numbers);
// Iterate over each item and log it
collection.each(item => console.log(item));
// Logs: 1, 2, 3, 4, 5, 6
// Take the first 3 items
const firstThree = collection.take(3).toArray();
// [1, 2, 3]
// Take the last 2 items
const lastTwo = collection.takeLast(2).toArray();
// [5, 6]
// Slice the collection from index 2 to 4
const sliced = collection.slice(2, 4).toArray();
// [3, 4]
// Reverse the collection
const reversed = collection.reverse().toArray();
// [6, 5, 4, 3, 2, 1]
// Splice the collection to remove 2 items from index 2 and add new items
const spliced = collection.splice(2, 2, 'a', 'b').toArray();
// [1, 2, 'a', 'b', 5, 6]
FAQs
`kp-mysql-models` is a lightweight, easy-to-use, and promise-based Node.js ORM tool designed for MySQL. It simplifies database interactions by offering features like model-based query building, CRUD operations, and support for advanced queries such as joi
The npm package kp-mysql-models receives a total of 7 weekly downloads. As such, kp-mysql-models popularity was classified as not popular.
We found that kp-mysql-models demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
Security News
The Linux Foundation is warning open source developers that compliance with global sanctions is mandatory, highlighting legal risks and restrictions on contributions.
Security News
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.