Skip to content

AdonisJs 5V: How to save data using fill({...}).related('...').saveMany([...]) #4376

Closed Answered by ekimkael
andre-ab asked this question in Help
Discussion options

You must be logged in to vote

Hello Andre,
in your Model you just have make it like that:

@manyToMany(() => Specialty, { pivotTable: 'employee_has_specialty' })
public specialities: ManyToMany<typeof Specialty>

and in your Controller you'll have to save first then attach specialities like this:

const employee = new Employee()
const payload = await request.validate(EmployeeValidator)
// or the way you get your data

const newEmployee = await employee.fill(payload).save()
await newEmployee.related('specialities').attach(payload.specialities)

in the update method make sure to detach before attach

const employee = await Employee.findOrFail(params.id)
const payload = await request.validate(EmployeeValidator)
// or the way …

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@andre-ab
Comment options

Answer selected by andre-ab
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Help
Labels
None yet
2 participants