How to get data from other table using a column data from a different table?

后端 未结 1 1883
渐次进展
渐次进展 2021-01-26 05:02

I have two tables:

table1

id | email
1 | email1
2 | email2

table2

userid | username
2      | user1
3      | user2


        
相关标签:
1条回答
  • 2021-01-26 05:34

    You should create model like this

    I assumed that you want to do one-by-one association. So this is it.

    api/models/Email.js

    attributes: {
        email : {
            type: 'email',
            unique: true
        },
        owner : {
            model:'user',  //here put your model name 
            unique: true   //put unique here because it's one by one association
       }
    }
    

    api/models/User.js

    attributes: {
       username : {
         type: 'string',
         unique: true
       },
       userEmail : {
          collection:'email', //here is also model name
          via: 'owner'
       }
    }
    

    Then

    Get user from email

    Email.find().populate('owner')
    

    Get email from user

    User.find().populate('userEmail')
    

    Now you can access to your data both from your two model.

    Try to print two command above you will see that your data contain the data from related table.

    Email.find().populate('owner').exec(function(err, records) {
        res.json(records)
    });
    

    This is my response.

    [
        {
            "owner": {
                "username": "test",
                "id": 1,
                "createdAt": "2016-11-23T13:45:06.000Z",
                "updatedAt": "2016-11-23T13:45:06.000Z"
            },
            "email": "test@test.com",
            "id": 1,
            "createdAt": "2016-11-23T13:45:06.000Z",
            "updatedAt": "2016-11-23T13:45:06.000Z"
        }
    ]
    

    More information : http://sailsjs.com/documentation/concepts/models-and-orm/associations/one-to-one

    0 讨论(0)
提交回复
热议问题