Sails.js协会

我从sails.js开始,我完全失去了我的SQL查询。

我有以下表格:

genres +-----------+--------------+------+-----+ | Field | Type | Null | Key | +-----------+--------------+------+-----+ | id | int(6) | NO | PRI | | name | varchar(100) | NO | | | slug | varchar(255) | NO | | | type | varchar(32) | NO | | | parent_id | int(11) | YES | MUL | +-----------+--------------+------+-----+ genres_radios +----------+--------+------+-----+ | Field | Type | Null | Key | +----------+--------+------+-----+ | genre_id | int(6) | NO | MUL | | radio_id | int(6) | NO | MUL | +----------+--------+------+-----+ radios +-----------+--------------+------+-----+ | Field | Type | Null | Key | +-----------+--------------+------+-----+ | id | int(5) | NO | PRI | | name | varchar(100) | NO | | | slug | varchar(100) | NO | | | url | varchar(100) | NO | | +-----------+--------------+------+-----+ 

我想检索收音机及其相关的stream派。 我设法使用Model.query(“Select * FROM …”)来做到这一点,但我想使用填充方法来做到这一点。 我看了一下文档,但是对于“via”,“through”,我有点困惑。

这应该做到这一点:

 // api/models/Genres.js module.exports = { attributes : { name : { type: 'string' }, slug : { type: 'string' }, type : { type: 'string' }, radios : { collection: 'Radios', through: 'genres_radios' } } } // api/models/Radios.js module.exports = { attributes : { name : { type: 'string' }, slug : { type: 'string' }, url : { type: 'string' }, genres : { collection: 'genre', through: 'genres_radios' } } } // api/models/Genres_radios.js module.exports = { attributes = { 'Genre_id': { columnName:'genre_id', type:'integer', foreignKey:'true', references:'genres', on:'id', via:'genres' }, 'Radio_id': { columnName:'radio_id', type:'integer', foreignKey:'true', references:'radios', on:'id', via:'radios' } } } 

然后你可以提出以下要求:

 Radio.findOne({name:"RadioName"}).populate("genres").then(function(radio){ console.log(radio); }) 

那么如果你遵循了Sails.js模型文档和许多关联文档,你的模型应该是这样的:

 // api/models/genre.js module.exports = { attributes : { name : { type: 'string' }, slug : { type: 'string' }, type : { type: 'string' }, radios : { collection: 'radio', via: 'genres' } } } // api/models/radio.js module.exports = { attributes : { name : { type: 'string' }, slug : { type: 'string' }, url : { type: 'string' }, genres : { collection: 'genre', via: 'radios' } } } 

水线将为您在内部创build多个查询表。 所有你需要得到你的收音机的stream派是填充“stream派”属性。

 Radio.findOne({name:"RadioName"}).populate("genres").then(function(radio){ console.log(radio); //radio.genres will have all the genres associated with this radio. }) 

我真的build议看看这么多的关联文档 。 他们正是你所需要的。