How to merge a relationships in adonisjs builder

I have two schemas documents and links.
My documents schema has many links:

Links structure:
document_a_code
document_b_code
type

Document structure:
code
name

I want to create a hasmany relationships where in referenced to both document_a_code and document_b_code columns

This is the exampl done in laravel.

public function userRelations() {
    return $this->hasMany('App\UserRelation');
}

public function relatedUserRelations() {
    return $this->hasMany('App\UserRelation', 'related_user_id');
}

public function allUserRelations() {
    return $this->userRelations->merge($this->relatedUserRelations);
}

How could I do the above example code in adonisjs

1 Like

Hi @kfa!

I don’t think Adonis has something like this built in. But some workaround would be to use .with()

allUserRelations() {
  return this.query().with('userRelations').with('relatedUserRelations')
}

If you have many of thos with’s you can make loop and loop over them and attach them to query

allUserRelations() {
  let relations = ['userRelations', 'relatedUserRelations']
  let query = this.query()
  relations.forEach((relation) => {
    query = query.with(relation)
  })
  return query
}
3 Likes

cool. I’ll try this.

Hello @McSneaky

I tried using your suggestions and it says

this.with is not a function

this is the example of my code

links () {
    return this.with('linksB').with('linksA')
}

hope to have feedback.

Yesh my bad. Was missing .query(). It should be this.query().with()

 links () {
    return this.query().with('linksB').with('linksA')
  }

that is my code now.

and still I got this error

"this.query is not a function"

I’ve done a pretty messy work around and so far it works. This is my approach.

const linksA = await document.linksA().fetch()
const linksB = await document.linksB().fetch()
const links = [].concat(linksA.rows, linksB.rows)

so far it works

1 Like