Objection.js Model Explained
const { Model } = require("objection");
const knexSingleton = require("../../MainDb");
Model.knex(knexSingleton.getKnexInstance());
class CMAttributeLibrary extends Model {
static get tableName() {
return "cm_attribute_library";
}
static get idColumn() {
return "cmAttributeLibraryId";
}
static beforeDelete(args) {
}
static get modifiers() {
return {};
}
}
module.exports = CMAttributeLibrary;
Objection.js Model Explained
Code Explanation
const { Model } = require("objection");
const knexSingleton = require("../../MainDb");
Model.knex(knexSingleton.getKnexInstance());
- Yaha Objection.js ka
Modelimport kiya gaya hai. knexSingleton.getKnexInstance()ke through ek Knex instance (jo DB se connect karta hai) pass kiya gaya hai, taki saare models ek hi DB connection use karein.
class CMAttributeLibrary extends Model {
static get tableName() {
return "cm_attribute_library";
}
static get idColumn() {
return "cmAttributeLibraryId";
}
- Ye class
CMAttributeLibraryek model hai jocm_attribute_librarytable ko represent karta hai. tableNamebatata hai kaunsa database table use ho raha hai.idColumnbatata hai primary key column ka naam (cmAttributeLibraryId).
static beforeDelete(args) {
}
- Ye ek lifecycle hook hai jo record delete hone se pehle chalega.
- Abhi empty hai, but tum yaha logic likh sakte ho (for example: related records delete karna ya check karna).
static get modifiers() {
return {};
}
modifiersek feature hai jisme tum custom query filters define kar sakte ho.- Abhi empty hai
{}, but tum yaha apni query shortcuts likh sakte ho. Example:static get modifiers() { return { onlyActive(query) { query.where("status", "active"); } } }Fir query me use kar sakte ho:CMAttributeLibrary.query().modify("onlyActive");
module.exports = CMAttributeLibrary;
- Last me model ko export kiya gaya hai taki dusre files me use ho sake.
Overall Summary
Ye code ek Objection.js model define karta hai jo cm_attribute_library table ko represent karta hai.
tableName→ table ka naamidColumn→ primary key columnbeforeDelete→ hook (delete hone se pehle logic)modifiers→ custom query filters- Knex instance ko globally link kiya gaya hai taki DB se queries chal sakein.
Leave a Reply