Muhammad Shahzad
Muhammad Shahzad

Reputation: 9652

Nodejs one table two models using loopback framework

I'm new in Nodejs, and start working in loopback framework.

My problem,

I have one table for users, and I want to make two models from this table like employee model and customer model.

// model-config.json

"users": {
    "dataSource": "mysqlDs",
    "public": false
  },

I have two different controllers "employee.controller.js","customer.controller.js" and now I'm trying to make two models form one table and using these models in specific controller.

Here is some code of both controllers.

//customer.controller.js
module.exports = function customer(app) { 
    var Customer = app.models.users;

 Customer.AddCustomer(data, function (err, data) {
                console.log(data);  
 });

}

//employee.controller.js
module.exports = function employee(app) { 
    var Employee= app.models.users;
}

when I called a my Customer model function "AddCustomer" in customer controller, it gave me the error "undefined"

here is customer model code:

module.exports = function (Customer) {

   Customer.AddCustomer = function (data, cb) {}
}

Model files

{
  "name": "customer",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true

  },   

"properties": {.....}
}

any solution?

Upvotes: 0

Views: 623

Answers (1)

notbrain
notbrain

Reputation: 3396

If you are going to use Loopback constructs, you will need to create your base user model (do not name it User, or it will interfere with the built-in User model that comes with Loopback.

So, your base model could be something like CustomUser, with a CustomUser.json basing the model on PersistedModel:

{
  "name": "CustomUser",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true

  },   

"properties": {.....}
}

Then create two new models that extend from CustomUser (instead of PersistedModel):

Customer.json

{
  "name": "Customer",
  "base": "CustomUser",
  "idInjection": true,
  "options": {
    "validateUpsert": true

  },   

"properties": {.....}
}

Employee.json:

{
  "name": "Employee",
  "base": "CustomUser",
  "idInjection": true,
  "options": {
    "validateUpsert": true

  },   

"properties": {.....}
}

When you run either datasource.automigrate() or datasource.autoupdate() on your sql database, this will create 3 tables, one for each model, but the two that have "base":"CustomUser" will have all the fields that are also in CustomUser, plus the fields you define on Customer and Employee, respectively.

Upvotes: 1

Related Questions