patio
patio copied to clipboard
Save not appending associated foreign key values
I'm trying to use the associations system to insert data into 3 tables...
projects -----< jobs -----< stages
fk_cols: project job
Here's the code I'm running (I'm generalizing the columns where possible):
const db = patio.createConnection('mysql://site:pwdhash@localhost:3306/my_db');
const Project = patio.addModel('projects').oneToMany('jobs');
const Job = patio.addModel('jobs').manyToOne('projects').oneToMany('stages');
const Stage = patio.addModel('stages').manyToOne('jobs');
Project.save({
name: 'test',
jobs: [{
blockNumber: 'P1300',
quantity: 1,
dimensions: '3x2x1',
material: '1730',
grind: 'FG',
stages: [{
name: 'design',
complete: false
}]
}]
}).chain(console.log, console.log);
The following error is produced:
QueryError : ER_NO_REFERENCED_ROW_2: Cannot add or update a child row: a foreign key constraint fails ("my_db"."jobs", CONSTRAINT "jobs_ibfk_1" FOREIGN KEY ("project") REFERENCES "projects" ("id") ON DELETE CASCADE ON UPDATE CASCADE): INSERT INTO "jobs" ("blockNumber", "quantity", "dimensions", "material", "grind") VALUES ('P1300', 1, '3x2x1', '1730', 'FG')
Any ideas on a cause & solution?
After doing more than a half effort read of the documentation... :sweat:
key : foreignKey in current model's table that references associated model's primary key. Defaults to : "{tableName}Id".
Now that that's sorted, is there a limit on how many elements this can take? I'm trying to add ~694 elements (10 stages in 63 jobs) and it is silently failing. I know the data is alright because the method I was using before I found this worked fine.
I don't think Patio enforces a limit. You may run into a memory issue but I would expect some sort of error.
The error handler is not being called?
I'm actually not too sure. I put a little console.log
in the callback functions (success & error) and both are triggered. In the case of the error callback however the object appears to be empty?
I hand wrote a test entry with 1 value for each table (nested under the first) and it still fails. Only the project
is inserted.
I have never tried doing deeply nested object like that. @doug-martin would you expect it to work? Any ideas?
Did you sync() your models? http://c2fo.io/patio/models.html
Yeah I did in my test.... Here's the new code
That shouldn't work at all. It should fail because I have unique columns set up that would mean the same job and stage can't be added twice or 3 times. The database ends up with one entry in each.
Since it does work however, I'll probably use this solution for now, so while I'm at it I have a quick quesiton - do I actually need error handlers in all the places I put console.log
?
No, the error should bubble up to the top level. So having an error handler at the top level should be fine.