Skip to content

Commit ca6bbba

Browse files
authored
Merge pull request #3 from octet-stream/feat/one-to-many
2 parents ee65fd6 + dc5b852 commit ca6bbba

File tree

3 files changed

+24
-5
lines changed

3 files changed

+24
-5
lines changed

.changeset/breezy-papayas-sniff.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"better-auth-mikro-orm": minor
3+
---
4+
5+
Support 1:m references

src/tests/entities/User.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,15 @@
1-
import {Entity, type Opt, Property, Unique} from "@mikro-orm/core"
1+
import {
2+
Collection,
3+
Entity,
4+
OneToMany,
5+
type Opt,
6+
Property,
7+
Unique
8+
} from "@mikro-orm/core"
29
import type {User as DatabaseUser} from "better-auth"
310

411
import {Base} from "./Base.js"
12+
import {Session} from "./Session.js"
513

614
@Entity()
715
export class User extends Base implements DatabaseUser {
@@ -14,4 +22,7 @@ export class User extends Base implements DatabaseUser {
1422

1523
@Property({type: "string"})
1624
name!: string
25+
26+
@OneToMany(() => Session, "user")
27+
sessions = new Collection<Session, this>(this)
1728
}

src/utils/adapterUtils.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,8 @@ export interface AdapterUtils {
7474
): Record<string, any>
7575
}
7676

77+
const ownReferences = [ReferenceKind.SCALAR, ReferenceKind.ONE_TO_MANY]
78+
7779
/**
7880
* Creates bunch of utilities for adapter
7981
*
@@ -111,13 +113,14 @@ export function createAdapterUtils(orm: MikroORM): AdapterUtils {
111113
fieldName: string
112114
): EntityProperty {
113115
const prop = metadata.props.find(prop => {
114-
if (prop.kind === ReferenceKind.SCALAR && prop.name === fieldName) {
116+
if (ownReferences.includes(prop.kind) && prop.name === fieldName) {
115117
return true
116118
}
117119

118120
if (
119-
(prop.kind === ReferenceKind.MANY_TO_ONE && prop.name === fieldName) ||
120-
prop.fieldNames.includes(naming.propertyToColumnName(fieldName))
121+
prop.kind === ReferenceKind.MANY_TO_ONE &&
122+
(prop.name === fieldName ||
123+
prop.fieldNames.includes(naming.propertyToColumnName(fieldName)))
121124
) {
122125
return true
123126
}
@@ -141,7 +144,7 @@ export function createAdapterUtils(orm: MikroORM): AdapterUtils {
141144
* @param prop - Property metadata
142145
*/
143146
function getReferencedColumnName(entityName: string, prop: EntityProperty) {
144-
if (prop.kind === ReferenceKind.SCALAR) {
147+
if (ownReferences.includes(prop.kind)) {
145148
return prop.name
146149
}
147150

0 commit comments

Comments
 (0)