Sequelize, problem getting associations to return

后端 未结 4 1685
旧时难觅i
旧时难觅i 2021-02-15 13:20

I\'m currently experimenting with Sequelize and have two objects, a Person and Position, When getting a list of persons I want to get their position. <

4条回答
  •  孤独总比滥情好
    2021-02-15 13:34

    This allow serialize a json for anywhere action about a model. Read it, very well, i think that is the best way

    sequelize-virtual-fields

    // define models 
    var Person = sequelize.define('Person', { name: Sequelize.STRING });
    var Task = sequelize.define('Task', {
    name: Sequelize.STRING,
    nameWithPerson: {
        type: Sequelize.VIRTUAL,
        get: function() { return this.name + ' (' + this.Person.name + ')' }
        attributes: [ 'name' ],
        include: [ { model: Person, attributes: [ 'name' ] } ],
        order: [ ['name'], [ Person, 'name' ] ]
    }
    });
    
    // define associations 
    Task.belongsTo(Person);
    Person.hasMany(Task);
    
    // activate virtual fields functionality 
    sequelize.initVirtualFields();
    

提交回复
热议问题