drizzle-team / drizzle-team/drizzle-orm

[BUG]: Field name overwrites join with `null` [Relationship builder]

Open
#640 5 comments 0 reactions 0 assignees View on GitHub
docs docs/improvements improvement rqb
Dominant language
TypeScript
Stars
35.8k
Forks
1.6k
Avg merge
2d 7h
Merged PRs (30d)
4

Description

### What version of `drizzle-orm` are you using?

0.26.1

### What version of `drizzle-kit` are you using?

0.18.1

### Describe the Bug

1. Have a field inside a table with the same DB-native name as another object
```ts
export const users = sqliteTable('users', {
id: text('id').primaryKey(),
});

export const usersRelations = relations(users, ({ many }) => ({
tokens: many(tokens),
}));

export const tokens = sqliteTable('tokens', {
id: integer('id').primaryKey(),
userId: text('user').notNull(),
// ^^^^
// Notice the field name here
// This is duplicate with the name below
});

export const tokensRelations = relations(tokens, ({ one }) => ({
user: one(users, {
// ^^^
// This duplicates the field above
fields: [tokens.userId],
references: [users.id],
}),
}));
```
2. Query the Token with the relational query builder:
```ts
const dbUser = await request.db.query.tokens.findFirst({
where: eq(tokens.id, 1),
with: {
user: {
// ^^^^
// This here is the issue, I assume Drizzle doesn't know which one to
// query
columns: {
id: true,
},
},
},
});
```
The types for `dbUser` is the following:
```ts
const dbUser: {
id: number;
userId: string;
user: {
id: string;
tokenType: string;
accessToken: string;
};
} | undefined
```
but at runtime the type is this:
```
{
id: 1,
userId: '81095245',
user: null
}
```

I'm not quite sure why `user` here is `null` but renaming the first field in the DB fixed it.

### Expected behavior

The object should not contain `null` at runtime.

### Environment & setup

Cloudflare Workers + Cloudflare D1 (SQLite)

### Notes

If anyone finds a better title, please suggest / edit it :)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.