简体   繁体   中英

SailsJS One to Many associations

Hi I'm building a Sails app with a couple of models in a one to many configuration. I've been able to create new instances of the models via the relationship, but it seems to be only working one way.

For reference (one) project can have (many) users.

/** Projects.js **/
name: {
    type: string
},

managers: {
    collection: 'Users',
    via: 'projects'
}

/** User.js **/
username: { 
    type: 'string'
},

projects { {
    model: 'Projects'
}

Using the following create method, results in the User have a reference to the Project, but no reference to the user is available to the Project. The managers reference is an array of user ids.

Project.create({ name: req.param('name'), managers: req.param('managers') }).exec(function newProject(err, results) {
    if (err) return res.json({ error: err });
    return res.json({ results: results });
});

And to retrieve the projects with their respective managers:

Project.findOne({ id: req.param('id') }).populate('managers').exec(function project(err, results) {
    if (err) return res.json({ error: err });
    return res.json({ results: results });
});

Shouldn't

managers: {
    collection: 'Users',
    via: 'projects'
}

be like this:

managers: {
    collection: 'User',
    via: 'projects'
}

?...

You refer the collection to the Model filename. Refer to this documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM