Skip to content

Commit

Permalink
feat(belongsTo): implement dissociate
Browse files Browse the repository at this point in the history
  • Loading branch information
thetutlage committed Oct 6, 2019
1 parent b51d0af commit 2e18430
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/Orm/Relations/BelongsTo/QueryBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,6 @@ export class BelongsToQueryBuilder
public async save (related: ModelContract, wrapInTransaction: boolean = true) {
if (Array.isArray(this._parent)) {
throw new Error('Cannot save with multiple parents')
return
}

/**
Expand All @@ -111,7 +110,7 @@ export class BelongsToQueryBuilder
trx = await this.client.transaction()
}

const callback = (parent, related) => {
const callback = (parent: ModelContract, related: ModelContract) => {
parent[this._relation.foreignKey] = this.$getRelatedValue(related, this._relation.localKey)
}

Expand All @@ -133,6 +132,12 @@ export class BelongsToQueryBuilder
* Remove relation
*/
public async dissociate () {
if (Array.isArray(this._parent)) {
throw new Error('Cannot save with multiple parents')
}

this._parent[this._relation.foreignKey] = null
await this._parent.save()
}

/**
Expand Down
Binary file added test-helpers/tmp/db.sqlite
Binary file not shown.
55 changes: 55 additions & 0 deletions test/orm/model-belongs-to.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1231,3 +1231,58 @@ test.group('Model | HasOne | persist', (group) => {
assert.isUndefined(profile.$trx)
})
})

test.group('Model | HasOne | dissociate', (group) => {
group.before(async () => {
db = getDb()
BaseModel = getBaseModel(ormAdapter(db))
await setup()
})

group.after(async () => {
await cleanup()
await db.manager.closeAll()
})

group.afterEach(async () => {
await resetTables()
})

test('dissociate relationship', async (assert) => {
class User extends BaseModel {
@column({ primary: true })
public id: number

@column()
public username: string
}

class Profile extends BaseModel {
@column({ primary: true })
public id: number

@column()
public userId: number

@column()
public displayName: string

@belongsTo(() => User)
public user: User
}

const user = new User()
user.username = 'virk'
await user.save()

const profile = new Profile()
profile.displayName = 'Hvirk'

await profile.related<'belongsTo', 'user'>('user').associate(user)
assert.isTrue(profile.$persisted)
assert.equal(user.id, profile.userId)

await profile.related<'belongsTo', 'user'>('user').dissociate()
assert.isNull(profile.userId)
})
})

0 comments on commit 2e18430

Please sign in to comment.