0
votes

Let's say I have an entity Company with a one-to-many relationship with entity Employee. I want to query for a company which would typically be done via:

return companyRepo.findOne(companyId, { relations: ["employees"]})

The above query will cause OOM issues, and a more efficient approach (approach number 2) is to do the following:

const company = await companyRepo.findOne(companyId);
const employees = await employeeRepo.find({ where: { companyId });
company.employees = employees;
return company;

Everything works except when I try to save (companyRepo.save(company)), when I try to save I get the following error:

Error: null value in column "company_id" of relation "employee" violates not-null constraint

Why is this happening, how can I get approach number 2 to work?

1

1 Answers

0
votes

Approach number two does work, the issue you're seeing is because you're most likely filtering the employees before setting company.employees. When you filter a relation then try to save it, typeorm will attempt to destroy the relationship between the employee and company (for the employees you filtered out), but if you have a not null constraint on the company_id in employee it will throw the error you're seeing. So make sure you're not doing a filter.