記錄是您從 .find()
或 .findOne()
取得的結果。每筆記錄都是一個可唯一識別的物件,與實體資料庫條目一一對應;例如,在 Oracle/MSSQL/PostgreSQL/MySQL 中的列、在 MongoDB 中的文件,或在 Redis 中的雜湊。
var records = await Order.find();
console.log('Found %d records', records.length);
if (records.length > 0) {
console.log('Found at least one record, and its `id` is:',records[0].id);
}
在 Sails 中,記錄只是字典(純 JavaScript 物件),這表示它們可以輕鬆地表示為 JSON。但您也可以使用 customToJSON
模型設定,自訂特定模型記錄的字串化方式。
除了電子郵件地址、電話號碼和出生日期等基本屬性資料外,Waterline 還可以使用關聯動態儲存和檢索連結的記錄集合。當在查詢中呼叫 .populate()
時,每個產生的記錄將包含一個或多個填充值。每個填充值都是查詢時連結到該特定關聯的記錄(或記錄陣列)的快照。
填充值的類型取決於關聯的種類
null
,或純 JavaScript 物件(如果它對應於「模型」關聯)例如,假設我們正在處理可愛小狼幼犬的訂單
var orders = await Order.find()
.populate('buyers') // a "collection" association
.populate('seller'); // a "model" association
// this array is a snapshot of the Customers who are associated with the first Order as "buyers"
console.log(orders[0].buyers);
// => [ {id: 1, name: 'Robb Stark'}, {id: 6, name: 'Arya Stark'} ]
// this object is a snapshot of the Company that is associated with the first Order as the "seller"
console.log(orders[0].seller);
// => { id: 42941, corporateName: 'WolvesRUs Inc.' }
// this array is empty because the second Order doesn't have any "buyers"
console.log(orders[1].buyers);
// => []
// this is `null` because there is no "seller" associated with the second Order
console.log(orders[1].seller);
// => null
下表顯示在不同情況下,從 .find()
或 .findOne()
呼叫返回的記錄中,您可以預期獲得的值。
沒有為關聯添加 .populate() 的情況 |
有 .populate() ,但未找到關聯記錄的情況 |
有 .populate() ,且找到關聯記錄的情況 |
|
---|---|---|---|
單數關聯(例如:seller ) |
此屬性在資料庫記錄中的任何值(通常為 null 或外鍵值) |
|
代表子記錄的 POJO |
複數關聯(例如:buyers ) |
undefined (鍵將不會存在) |
[] (空陣列) |
代表子記錄的 POJO 陣列 |
若要修改特定記錄或一組記錄的填充值,請呼叫 .addToCollection()、.removeFromCollection() 或 .replaceCollection() 模型方法。