[Postgres - Question]
Closed this issue · 3 comments
Hi,
I'm trying to fetch Accountplan id (foreign key) from table Company. The generated entity
@ManyToOne(() => Accountplan, (accountplan) => accountplan.companies)
@JoinColumn([{ name: "defaultaccountplan", referencedColumnName: "id" }])
defaultaccountplan: Accountplan;
Code:
const company = await getRepository(Company).findOne({
where: {
orgid: id,
},
});
console.log(company.id);
console.log(company.defaultaccountplan.id);
Company.id works fine, but company.defaultaccountplan.id and company.defaultaccountplan returns undefined?
If I add Column to entity I can use company.defaultaccountplan to get id
@Column("integer", { name: "defaultaccountplan", nullable: true })
defaultaccountplan: number | null;
Can anyone tell me what i'm doing wrong?
Sorry for the delay.
It looks like defaultaccountplan
relation isn't loaded - it's another table and you're only fetching only the main table. You're probably looking for relations
in https://typeorm.io/#/find-options
Thanks! It fixed the problem.
@Kononnable do I always need to load the relation just to get the defaultaccountplan id?. The defaultaccountplan id already exist in the Company table. It seems a bit unessesay to do i left join when the id already exist.
LEFT JOIN "public"."accountplan" "Company__defaultaccountplan" ON "Company__defaultaccountplan"."id"="Company"."defaultaccountplan"
Seems to be the same problem as typeorm/typeorm#536. It maybe would be nice if the model-generator added an id column if the user only wanted the relation key (id) and not the entire relation.
You're looking for https://typeorm.io/#/relations-faq/how-to-use-relation-id-without-joining-relation or https://typeorm.io/#/decorator-reference/relationid.
Typeorm doesn't create objects for related tables even if it can guess some of the content.