記錄、關聯與階層
一條記錄表示一個業務物件,例如任務、客戶或訂單。Facade API 覆蓋圍繞記錄的各項操作:批次寫入、分頁讀取、關聯其他表以及組織父子記錄。
建立與讀取記錄
TypeScript
const base = univerAPI.getActiveBase()if (!base) throw new Error('Open a Base first')const table = base.insertTable('Tasks', { primaryFieldName: 'Title' })const titleId = table.getPrimaryFieldId()const records = table.addRecords([ { values: { [titleId]: 'Write documentation' } }, { values: { [titleId]: 'Review examples' } },])records[0].setValue(titleId, 'Publish documentation')const page = table.queryRecords({ offset: 0, limit: 20 })console.log(page.total, page.records)記錄值預設以欄位 ID 為鍵。如果資料以欄位名為鍵,則傳入 univerAPI.Enum.BaseFieldKeyEnum.Name。queryRecords() 只查詢已經載入到本地的資料,不會從後端取得分頁。要按檢視範圍讀取記錄,使用 viewId;要指定排序,使用 sort。
批次刪除記錄使用 table.deleteRecords(recordIds),複製記錄使用 record.duplicate()。這兩種操作都經過命令系統,因此都支援撤銷和重做。
搜尋記錄
在選定欄位中搜尋文字:
TypeScript
const matches = table.search({ query: 'documentation', fieldIds: [titleId], limit: 20 })console.log(matches)關聯另一個資料表
以下範例把每個任務關聯到一個專案:
TypeScript
const projects = base.insertTable('Projects', { primaryFieldName: 'Name' })const project = projects.addRecord({ [projects.getPrimaryFieldId()]: 'Website' })const projectField = table.addField('Project', univerAPI.Enum.BaseFieldType.RecordLink, { field: { config: { targetTableId: projects.getId(), multiple: false } },})records[0].setLinkedRecordIds(projectField.getId(), [project.getId()])console.log(records[0].getLinkedRecordIds(projectField.getId()))關聯目標必須屬於同一個 Base。要允許關聯多條記錄,請設定 multiple: true;displayFieldId 決定顯示的標籤;pickerFieldIds 為選擇器提供補充上下文。讀寫記錄 ID 應透過關聯 API 完成,不要直接拼接內部儲存字串。
父子記錄
以下範例把 API 檢查設為文件任務的子記錄:
TypeScript
const parent = records[0]const parentFieldId = table.getHierarchyFieldId()const child = parent.addChild(parentFieldId, { [titleId]: 'Check API examples' })console.log(child.getParent(parentFieldId)?.getId())child.setParent(parentFieldId, null)新增第一條子記錄時,所需的父級關聯欄位會自動建立。使用 getChildren()、getAncestors() 和 getDescendants() 可以讀回這些關係。層級最多五層。記錄不能將自身設為父級,迴圈引用會被拒絕。無效操作會丟擲錯誤,因此應捕獲錯誤,並在介面上向使用者提示。
層級屬於表資料,切換或篩選檢視都不會改變層級。其餘方法參見 Bases Facade。
你覺得這篇文檔如何?