Skip to content
Snippets Groups Projects
Commit 12d043da authored by Thibaut DE SAIVRE's avatar Thibaut DE SAIVRE Committed by Thomas SAUVAGE
Browse files

update model relation

parent 71cce4db
No related branches found
No related tags found
1 merge request!1Idiomatic relations
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import Event from 'App/Models/Event'
import { Tree } from 'App/Utils/types'
/** Get all events */
export const getAllRoots = async ({ response }: HttpContextContract) => {
......@@ -10,19 +9,10 @@ export const getAllRoots = async ({ response }: HttpContextContract) => {
}
/** Recursively gives a list of sons events */
const getSons = async (id: number): Promise<Tree<Event>> => {
const event = await Event.find(id)
const getSons = async (id: number) => {
const event = await Event.findOrFail(id) // Use this to throw an error automatically when the item is not found
if (!event) {
throw new Error('Event not found')
}
let sons: Tree<Event>[] = []
for (const sonId of event.sonIds) {
sons.push(await getSons(sonId))
}
return { father: event, sons }
return event.related('children').query() // Query level 1 children like this (this is not recursive)
}
/** Get all sons of a given event, using params */
......@@ -64,9 +54,7 @@ export const createEvent = async ({ request, response }: HttpContextContract) =>
return response.badRequest({ error: 'Father not found' })
}
const event = await Event.create({ ...data, isRoot: false })
father.sonIds.push(event.id)
await Event.create({ ...data, isRoot: false, parentId: father.id })
await father.save()
return response.created({ message: 'Son event created' })
......
import { BaseModel, column } from '@ioc:Adonis/Lucid/Orm'
import { BaseModel, HasMany, column, hasMany } from '@ioc:Adonis/Lucid/Orm'
import { DateTime } from 'luxon'
export default class Event extends BaseModel {
......@@ -12,7 +12,13 @@ export default class Event extends BaseModel {
public thumbnailId: number
@column()
public sonIds: number[] // Represents the ids of the sons of the event (tree structure)
public parentId: number | null
@hasMany(() => Event, {
foreignKey: 'parentId', // An Event is a child of this one if its parentId is equal to this Event's id
localKey: 'id',
})
public children: HasMany<typeof Event>
@column()
public isRoot: boolean // Represents if the event is the root of the tree
......
......@@ -9,7 +9,8 @@ export default class extends BaseSchema {
table.string('name', 255).notNullable()
table.bigint('thumbnail_id').notNullable()
table.specificType('son_ids', 'integer[]').notNullable().defaultTo('{}')
// NOTE : on delete cascade will delete child events when the parent id they point to becomes invalid
table.integer('parent_id').nullable().references('id').inTable('events').onDelete('CASCADE')
table.boolean('is_root').notNullable()
/**
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment