can i use softdeletes in adonis v5 #1791
Replies: 3 comments 5 replies
-
It's not a built-in feature in Adonisjs yet but you can use the hooks API to achieve this.
Then in your model you add @beforeDelete, @beforeFind and @beforeFetch hooks lie so:
I am not entirely sure about the behaviour of the @beforeDelete hook though. An alternative would be to override the default delete method in your model. for example:
|
Beta Was this translation helpful? Give feedback.
-
@kmihiranga where are you on this now? Is soft delete a planned feature in adonis5? |
Beta Was this translation helpful? Give feedback.
-
https://github.com/adonisjs/core/issues/3411 Finally, I solved the problem temporarily in this way: define Base in Models import { DateTime } from 'luxon'
import { BaseModel, beforeFetch, beforeFind, column } from '@ioc:Adonis/Lucid/Orm'
import CamelCaseNamingStrategy from 'App/Helper/CamelCaseNamingStrategy'
import { softDelete, softDeleteQuery } from 'App/Services/SoftDelete'
export default class Base extends BaseModel {
public static namingStrategy = new CamelCaseNamingStrategy() // this maybe not needed for you
@column.dateTime({ serializeAs: null })
public deletedAt: DateTime
@beforeFind()
public static softDeletesFind = softDeleteQuery
@beforeFetch()
public static softDeletesFetch = softDeleteQuery
public async softDelete(column?: string) {
await softDelete(this, column)
}
} app/Services/SoftDelete.ts import { BaseModel, LucidRow, ModelQueryBuilderContract } from '@ioc:Adonis/Lucid/Orm'
import { DateTime } from 'luxon'
export const softDeleteQuery = (query: ModelQueryBuilderContract<typeof BaseModel>) => {
query.whereNull(`${query.model.table}.deletedAt`)
}
export const softDelete = async (row: LucidRow, column: string = 'deletedAt') => {
row[column] = DateTime.local()
await row.save()
return
} hope can help someone. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
i have used Laravel many years and i used soft deletes to my many projects. can i know if there any way to use like this soft deletes in Adonis js. i read the documentation but i couldn't get any point using this feature.
Beta Was this translation helpful? Give feedback.
All reactions