IDBObjectStore.keyPath

admin發表於2019-09-18

此屬性可以返回物件倉庫中規定記錄的主鍵路徑。

keyPath屬性可以通過createObjectStore()方法的第二個引數規定。

關於createObjectStore()具體用參閱createObjectStore() 建立物件倉庫一章節。

語法結構:

[JavaScript] 純文字檢視 複製程式碼
let keyPath = objectStore.keyPath;

非常簡單的一個屬性,看如下程式碼例項:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script>
let request = window.indexedDB.open("antzone", 1);
request.onupgradeneeded = (ev) => {
  let db = ev.target.result;
  if (!db.objectStoreNames.contains('students')) {
    let objectStore = db.createObjectStore('students',{keyPath:"id"});
    objectStore.createIndex("xingbie","sex",{ unique: false });
  }
}

request.onsuccess = (ev) => {
  let db = ev.target.result;
  let transaction = db.transaction(['students'], 'readonly');
  let objectStore = transaction.objectStore('students');
  console.log(objectStore.keyPath);
}
</script>
</head>
<body>
  <p>列印物件倉庫的主鍵</p>
</body>
</html>

程式碼執行效果截圖如下:

a:3:{s:3:\"pic\";s:43:\"portal/201909/18/160658yeubnq10pnugnzln.jpg\";s:5:\"thumb\";s:0:\"\";s:6:\"remote\";N;}

可以看到物件倉庫的主鍵是id,通過createObjectStore()方法第二個引數設定。