Shouldn't the fields related to the Query API be of type <T | undefined> ?

When getting related fields using the findFirst or findMany methods, the appended fields that I bring with "with" should not be of type <T | undefined> so that in case nothing is found it is safe.
Solution:
As far as I can tell, the type of the relation field is nullable when the foreign key column is nullable in the schema (so may not always exist), and non-nullable if the foreign key always exists.
Jump to solution
3 Replies
kbemaster
kbemasterOP9mo ago
const lesson = db.query.lessonTable
.findFirst({
where: (columns, { eq }) => eq(columns.id, "lessonId"),
with:{
author: true
},
});

// lesson.author.name -> error because author was undefined and I tried to access .name
const lesson = db.query.lessonTable
.findFirst({
where: (columns, { eq }) => eq(columns.id, "lessonId"),
with:{
author: true
},
});

// lesson.author.name -> error because author was undefined and I tried to access .name
Solution
piechart
piechart9mo ago
As far as I can tell, the type of the relation field is nullable when the foreign key column is nullable in the schema (so may not always exist), and non-nullable if the foreign key always exists.
kbemaster
kbemasterOP9mo ago
I will try that Thanks!
Want results from more Discord servers?
Add your server