我同意雷納託。你基本上有一個多對多的場景。作者可以寫幾本書,相反,書可以有多個作者。
不幸的是,Google Datastore中沒有多對多關係的顯式機制。但是你仍然可以構建你的實體來建模關係。
例如,而不是使用通過祖先路徑的層次模型,添加一個數組來存儲引用作者的實體按鍵,可能是這個樣子你的書的實體:
book_key = datastore.key "Book"
author_key1 = datastore.key "Author", "john"
author_key2 = datastore.key "Author", "jane"
author_entity1 = datastore.entity author_key1 do |t|
t["name"] = "Doe, John"
end
author_entity2 = datastore.entity author_key2 do |t|
t["name"] = "Doe, Jane"
end
datastore.save(author_entity1, author_entity2)
而且在數組屬性Book實體會是這個樣子:
book_entity = datastore.entity book_key do |t|
t["authors"] = [author_key1, author_key2]
end
如果你想知道與筆者李四在你的數據庫相關聯的所有你需要做的就是查詢「作者」數組屬性的所有書籍:
query = Google::Cloud::Datastore::Query.new
query.kind("Book").
where("authors", "=", datastore.key("Author","john"))
books_by_john = datastore.run query
請注意,我本可以走另一條路,並在作者實體上創建一個Book鍵數組。但是,如果我走了這條路線,並試圖模仿一個多產的作家,比如說說斯蒂芬·金......那麼作者實體最終會因爲對圖書實體的關鍵引用而變得非常臃腫,所以你必須對關係的哪一方進行選擇你添加數組並嘗試尋找不太可能膨脹的實體。