如果一本書可以有很多標籤,並且標籤可以有很多書,這聽起來像是需要hasAndBelongsToMany關係。這種關係對於沒有任何額外有效載荷的多對多來說是很好的。
通用/模型/ book.json
{
"name": "Book",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"Title": {
"type": "string",
"required": true
},
"Author": {
"type": "string"
}
},
"validations": [],
"relations": {
"tags": {
"type": "hasAndBelongsToMany",
"model": "Tag",
"foreignKey": ""
}
},
"acls": [],
"methods": {}
}
通用/模型/ tag.json
{
"name": "Tag",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"Name": {
"type": "string",
"required": true
}
},
"validations": [],
"relations": {
"books": {
"type": "hasAndBelongsToMany",
"model": "Book",
"foreignKey": ""
}
},
"acls": [],
"methods": {}
}
如何訪問呢?以下是一個啓動腳本示例,它創建一些標籤和書籍,並訪問它們。
服務器的/ boot/seed.js
var async = require('async');
module.exports = function(app) {
var Tag = app.models.Tag;
var Book = app.models.Book;
var tags = [{Name: "Scifi"}, {Name: "Adventure"}];
Book.create({Title: "Twenty Thousand Leagues Under the Sea", author: "Jules Verne"}, function(err, book){
console.log('Book: ' + book);
async.each(tags, function(tag, done){
book.tags.create(tag, done);
}, function(err){
//Book > Tag
console.log("Book " + book.Title + " has these tags: ");
console.log(book.tags())
//Tag > Book
Tag.findOne({where: {Name: "Scifi"}, include: 'books'},function(err, foundTag){
console.log(" - Tag " + foundTag.Name + " has these books:");
console.log(foundTag.books());
});
});
});
};
輸出:
Book Twenty Thousand Leagues Under the Sea has these tags:
[ { Name: 'Scifi', id: 1 }, { Name: 'Adventure', id: 2 } ]
Tag Scifi has these books:
[ {
Title: 'Twenty Thousand Leagues Under the Sea',
author: 'Jules Verne',
id: 1
} ]