2015-12-11 83 views
0

我有一個模型Bookloopback:如何根據關係的屬性加載模型實例

Book可以有多個標籤,所以通過BookTags

一個的hasMany關係Tag現在,我怎麼加載所有Book情況與標籤「歷史」(例如)? 這應該是微不足道的,但我找不到。

在文檔中,只有屬性值的示例(如字符串,布爾值等),但沒有用於通過關係加載的示例。有加載關係的include過濾器,但它應該適用於加載關係實例,這是別的東西(AFAI理解);

我想:

Book.find({ 
    where: {tags: {name: "history"}} 
}, function(err, books) { 
} 

但是,這並不在所有的工作。 我的下一個賭注試圖通過ID加載標籤,並嘗試通過對象進行過濾,但我甚至不知道如何做到這一點,因爲沒有「包含」運營商在where子句文檔中: https://docs.strongloop.com/display/public/LB/Where+filter#Wherefilter-inq

最終的解決方法是:通過名稱

  • 負荷標籤
  • 負載與標籤ID的所有BookTags的情況下,拿書IDS
  • 負荷所有的書與那些IDS

似乎麻煩,並建議應該有一個更優雅的解決方案?

回答

0

如果一本書可以有很多標籤,並且標籤可以有很多書,這聽起來像是需要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 
} ] 
相關問題