【发布时间】:2019-08-22 22:29:23
【问题描述】:
我正在创建从 Google 应用制作工具到 Google 文档模板的文档合并(邮件合并)。合并一条记录时我可以成功,但是如何将多条记录合并到一个文档中?
我有一个 purchase_orders 父记录,其中有几个 purchase_order_line_items 子记录,但我似乎无法将所有这些记录合并到一个文档中。
Johan W 提出了一个类似的问题 (Document Merge with Google App Maker),Markus Malessa 和 Pavel Shkleinik 给出了全面的回答(谢谢!)。但是,它仅适用于合并单个记录的情况。
我试图通过使用第二个for 循环来获取所有关联子记录的数据,从而建立他们的答案。脚本运行但似乎只合并了第一个子记录;不是全部。
这是我尝试使用的服务器端代码示例:
function Export(key, key2) {
// Get the parent record by its key, which was passed by the first parameter above
var record = app.models.Purchase_Orders.getRecord(key);
// Get the first child record by its key, which was passed by the second parameter above
var childRecord = app.models.Purchase_Order_Line_Items.getRecord(key2);
// Get the Google Document which will be used as a template for this merge
var templateId = '1Xbt8camqHJYrhBnx0a6G2-RvTvybqU0PclHifcdiLLA';
//Set the filename of the new merge document to be created
var filename = 'Document for Customer ' + new Date();
//Make a copy of the template to use as the merge document
var copyFile = DriveApp.getFileById(templateId).makeCopy(filename);
//Get the Google Docs ID of the newly created merge document
var copyDoc = DocumentApp.openById(copyFile.getId());
var copyBody = copyDoc.getBody();
// Replace the field names in the template with the field data from the parent record
var fields = app.metadata.models.Purchase_Orders.fields;
for (var i in fields) {
console.log(i);
var text = '<<' + fields[i].name + '>>';
var data = record[fields[i].name];
if (data !== null) {
copyBody.replaceText(text, data);
} else {
// do nothing
}
}
// Replace the field names in the template with the field data from the child records
childFields = app.metadata.models.Purchase_Order_Line_Items.fields;
for (i in childFields) {
console.log(i);
var childtext = '<<' + childFields[i].name + '>>';
var childdata = childRecord[childFields[i].name];
if (childdata !== null) {
copyBody.replaceText(childtext, childdata);
} else {
// do nothing
}
}
}
如何改进我的代码,以便将所有关联的子记录合并到一个文档中?
如何设置我的 Google 文档模板以适应任意数量的子记录?
【问题讨论】:
标签: javascript sql google-apps-script merge google-app-maker