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 Model import 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 CMAttributeLibrary ek model hai jo cm_attribute_library table ko represent karta hai.
  • tableName batata hai kaunsa database table use ho raha hai.
  • idColumn batata 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 {};
  }
  • modifiers ek 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 naam
  • idColumn → primary key column
  • beforeDelete → hook (delete hone se pehle logic)
  • modifiers → custom query filters
  • Knex instance ko globally link kiya gaya hai taki DB se queries chal sakein.
MeCoderHu
https://mecoderhu.com

Leave a Reply