biggora / caminte

Cross-db ORM for NodeJS
http://www.camintejs.com/
MIT License
1.08k stars 119 forks source link

Relation problem #187

Closed wwardaww closed 6 years ago

wwardaww commented 6 years ago

Hello,

when i try get user's account like this :

... function (err,user) {
      res.json(user.account());
  });

it just return account_id

here my association & user model

var Users = schema.define('users', {
        id : { type : schema.Number },
        account_id : { type : schema.Number },
        is_active : { type : schema.Number },
        name : { type : schema.String },
        surname : { type : schema.String },
        email : { type : schema.String },
        password : { type : schema.String }
    },{
        primaryKeys:['id']
    });
    // additional methods and validation here
    Users.prototype.getFullName = this.name + ' ' + this.surname;
    Users.scope('active',{is_active:1, status:'a'});
    var Account = require('./AccountsModel');
    Users.belongsTo(Account,{as:'account',foreignKey: 'account_id'});
    //Relations
    return Users;

And when i try to get like this :

function (err,user) {
      user.account(function (err,acc) {
          res.json(acc)
      })

im getting error :

 anotherClass.schema.defineForeignKey(anotherClass.modelName, fk);
                        ^

TypeError: Cannot read property 'defineForeignKey' of undefined

How can i get my user's account?

wwardaww commented 6 years ago

The solition is :

in models/relations.js (if you haven't create one)

module.exports.load = function (models) {
    var caminte = require('caminte');
    // setup relations here
    var Accounts = caminte.model('Accounts');
    var Users = caminte.model('Users');

    Accounts.hasMany(Users,{as:'users',foreignKey: 'account_id'});
    Users.belongsTo(Accounts,{as:'account',foreignKey: 'account_id'});

};

in app.js or server.js (or your main script file)

...
var models = require('./models');
models.init(app);
//add this lines
var relations = require('./models/relations');
relations.load(models);