Problem with associate() function

Hello Adonis friends,

I’m having an issue trying to associate two models on my project. I have Docs and I have Users. I just want to relate existing users to existing docs and disassociate.

This is my controller:

async associarDocUser() {

        const user = await User.find(1)
        const doc = await Docs.find(6)

        await doc.user().associate(user)

        return user;
    }

This I have in my user model:

docs() {
    return this.belongsToMany('App/Models/Doc')
  }

This is what I have in my Docs:

users() {
        return this.belongsToMany('App/Models/User')
    }

This is my pivot table:

up() {
    this.create('doc_user', (table) => {
      table.increments()
      table.integer('doc_id').unsigned().references('docs.id').onDelete('cascade').index('doc_id').notNullable()
      table.integer('user_id').unsigned().references('users.id').onDelete('cascade').index('user_id').notNullable()
      table.timestamps()
    })
  }

The error I get:

What is my idea: Create a table that I can send a request to my controller to associate a doc to a user and to disassociate too.

I’m not trying to create something and relate, but assoaciate existing data.

What I’m doing wrong?

Thank you.

just call users() instead of user, it is a name of your relation function

2 Likes

Hi Keef3ear,

Trying to call users() I got the following error:

doc.users(…).associate is not a function

My controller:

const user = await User.find(1)
const doc = await Docs.find(6)
await doc.users().associate(user)

The associate method is exclusive to the belongsTo
Not to belongsToMany

2 Likes

Oh, I got it. So that’s the problem.

Thanks for the help!

Any suggestion of what can I do to creates the relationships? The guides that I found on the web was most focused at storing new data, and I have to relate that I already have.

u can just

const privot_item = await PivotModel.create({first_item_id: first_item.id, second_item_id = second_item.id})

Or make your own function in model and call it like item.mySetRelationFunc(related_item)
It is many ways to do what you want)

Hey keef3ar and communit, I found the solution!

If someone is experiencing the same, I found the easiest way to associate and disassociate.

This is my updated controller methods:

    async associateDocUser({ view, params }) {

        const user = await User.find(params.userId)
        const doc = await Docs.find(params.docId)

        await doc.users().attach(user.id)

        return user;
    }

    async disassociateDocUser({ view, params }) {

        const user = await User.find(params.userId)
        const doc = await Docs.find(params.docId)

        await doc.users().detach(user.id)

        return user;
    }

The remaining files still the same.

Thanks for helping!

pretty solution, but too many database requests for create one relation. It is no matter in common cases, so solution will work fine)

1 Like