Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HasMany relation not working in Adonis framework using mongodb database #231

Open
vikas-ukani opened this issue Nov 16, 2019 · 2 comments
Open

Comments

@vikas-ukani
Copy link

In my case, hasMany relation not working
database like

Users table

{
    "_id" : ObjectId("5dc5617ac22c2921fc32b1f0"),
    "name" : "vikas",
    "email" : "[email protected]",
    "contact_ids" : [ 
        "5dc5572ee6143821e43ece31"
    ],
     
    "created_at" : ISODate("2019-11-08T12:37:12.452Z"),
    "updated_at" : ISODate("2019-11-08T12:37:12.456Z")
}

Contact Table

{
    "_id" : ObjectId("5dc5572ee6143821e43ece31"),
    "name" : "vikas Contacts",
    "mobile" : 95754681658,
    "user_id" : "5dc5617ac22c2921fc32b1f0",
    "created_at" : ISODate("2019-11-08T11:53:15.781Z"),
    "updated_at" : ISODate("2019-11-08T11:53:15.786Z")
}

And, I'm applying relation to USERS model

User.js // model

  // get many contacts  
contacts() {
    return this.belongsToMany('App/Models/Contact', '_id', 'contact_ids')
    // hasMany(relatedModel, primaryKey, foreignKey)
  }

And, The final result is // OUTPUT

{
            "_id": "5dc5617ac22c2921fc32b1f0",
            "name": "vikas",
            "email": "[email protected]",
            "contact_ids": [
                "5dc5572ee6143821e43ece31"
            ],
            "password": "$2a$10$jiSfRAqDWlHv8yie3VBm3eWo.flT09xiOq8vORtSlwKvrJTM5qqPy",
            "created_at": "2019-11-08T12:37:12.452Z",
            "updated_at": "2019-11-08T12:37:12.456Z",
            "contacts": []
        }

When, I applying has many relations it doesn't show contacts list in an array

@duyluonglc
Copy link
Owner

@vikas-ukani try

const class User extends Model {
  contacts() {
    return this.hasMany('App/Models/Contact')
  }
}

const class Contact extends Model {
  static get objectIds () { return ['_id', 'user_id'] }
  user() {
    return this.belongsTo('App/Models/User')
  }
}

and remove contact_ids field
make sure your user_id field in contacts collection is stored as objectid

@golinmarq
Copy link

@vikas-ukani try

const class User extends Model {
  contacts() {
    return this.hasMany('App/Models/Contact')
  }
}

const class Contact extends Model {
  static get objectIds () { return ['_id', 'user_id'] }
  user() {
    return this.belongsTo('App/Models/User')
  }
}

and remove contact_ids field
make sure your user_id field in contacts collection is stored as objectid

I did this but it doesn't work 🙁

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants