I have a data model, Material, that has related chemicalProperty model. Each material may have several chemical properties. I want the users to be able to create a new Material record based on an existing one and to create at the same time a copy of its related chemicalProperty records to go along.
I know how to create several records from an array and I know how to make a query. Is there a way to create an array from a query? or is there another way to copy several records changing the forgein key in the process?
Here is the code I have right now.
Any help is appreciated.
function duplicateChemicalProperties(oldMaterialId, newMaterialId) {
/* var query = app.models.Propiedad_Quimica.newQuery();
* query.filters.Material_fk._equals = oldMaterialId;
* var recordData = query.run()[0];*/
var recordData = [
["1",new Date,userId,new Date,userId,"H2O",,"2",,".5","algun tipo de tolerancia","comentarios"],
["2",new Date,userId,new Date,userId,"Algodon de azucar ",,"6",,"10","tolerancia","Notas"]
];
var records = [];
for (var i = 0; i < recordData.length; i++) {
var record = app.models.Propiedad_Quimica.newRecord();
record.Material_fk = newMaterialId;
record.Fecha_Creacion = recordData[i][1];
record.Usuario_Creacion = recordData[i][2];
record.Fecha_Edicion = recordData[i][3];
record.Usuario_Edicion = recordData[i][4];
record.Analisis = recordData[i][5];
record.P_Min = recordData[i][6];
record.P_Max = recordData[i][7];
record.P_Tipico = recordData[i][8];
record.Tolerancia = recordData[i][9];
record.Tipo_de_tolerancia = recordData[i][10];
record.Comentarios = recordData[i][11];
records.push(record);
}
app.saveRecords(records);
}
This should work
function duplicateChemicalProperties(oldMaterialId, newMaterialId) {
var query = app.models.Propiedad_Quimica.newQuery();
query.filters.Material_fk._equals = oldMaterialId;
var existingRecords = query.run();
var newRecords = [];
for (var i = 0; i < existingRecords.length; i++) {
var existingRecord = existingRecords[i];
var newRecord = app.models.Propiedad_Quimica.newRecord();
newRecord.Material_fk = newMaterialId;
newRecord.Fecha_Creacion = existingRecord.Fecha_Creacion;
newRecord.Usuario_Creacion = existingRecord.Usuario_Creacion;
...
newRecords.push(newRecord);
}
app.saveRecords(newRecords);
}
Depending on the data flow the algorithm could be optimized with prefetches and Models Metadata API