Help understanding relations

Hey all, just trying to get my head around relations. In this example we have a one-to-many relationship:
export const users = mysqlTable("users", {
id: serial("id").primaryKey(),
username: varchar("username", { length: 120 }),
});

export const blocks = mysqlTable("blocks", {
id: serial("id").primaryKey(),
block_type: int("type"),
user_id: int("user_id"),
});

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

(async () => {
const user = await db.query.users.findFirst({
where: eq(users.username, "johnsmith"),
with: {
pagebuilder: true,
},
});
// user.pagebuilder[0].block_type ☑️
})();
export const users = mysqlTable("users", {
id: serial("id").primaryKey(),
username: varchar("username", { length: 120 }),
});

export const blocks = mysqlTable("blocks", {
id: serial("id").primaryKey(),
block_type: int("type"),
user_id: int("user_id"),
});

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

(async () => {
const user = await db.query.users.findFirst({
where: eq(users.username, "johnsmith"),
with: {
pagebuilder: true,
},
});
// user.pagebuilder[0].block_type ☑️
})();
How is the query 'joining' the tables when I havent defined which columns are related. Or in this case do 'all' block rows get attached?
2 Replies
d1ge
d1ge15mo ago
Try:
const query = await db.query.users.findFirst({
where: eq(users.username, "johnsmith"),
with: {
pagebuilder: true,
},
}).toSQL()

console.log(query);
const query = await db.query.users.findFirst({
where: eq(users.username, "johnsmith"),
with: {
pagebuilder: true,
},
}).toSQL()

console.log(query);
To see what its doing behind the scenes 🙂 Might explain it all!
Jim
JimOP15mo ago
Good tip for a beginner like me thank you!
Want results from more Discord servers?
Add your server