レコードとは、.find()
または.findOne()
から返されるデータです。各レコードは一意に識別可能なオブジェクトであり、物理的なデータベースエントリ(例:Oracle/MSSQL/PostgreSQL/MySQLの行、MongoDBのドキュメント、Redisのハッシュ)と1対1に対応します。
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()
がクエリで呼び出されると、結果の各レコードには1つ以上のポピュレートされた値が含まれます。これらのポピュレートされた値のそれぞれは、クエリ時のその特定の関連付けにリンクされているレコード(またはレコードの配列)のスナップショットです。
ポピュレートされた値の型は、それがどのような種類の関連付けであるかに依存します
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 または外部キー値) |
null |
子レコードを表すPOJO |
複数関連付け(例:buyers ) |
undefined (キーは存在しません) |
[] (空の配列) |
子レコードを表すPOJOの配列 |
特定のレコードまたはレコードセットのポピュレートされた値を変更するには、.addToCollection()、.removeFromCollection()、または.replaceCollection()モデルメソッドを呼び出します。