duyluonglc / lucid-mongo

Mongodb ODM for adonis framework
325 stars 61 forks source link

Not proper instantiation for PivotModel.query #209

Open erisrayanesh opened 5 years ago

erisrayanesh commented 5 years ago

Hey, Good job guys. To update a pivot table on BelongsToMany relation I tried this:

// the variable chat is an instance of a model called Chat
await chat.users().pivotQuery()
        .where({'user_id': this.auth.user.primaryKeyValue})
                .update({'last_seen_at': new Date()});

this raise a TypeError: fakeModel._setUpdatedAt is not a function

After couple of minutes of debugging and logging I found that this:

const result = await chat.users().pivotQuery().fetch()

returns all documents of the pivot table. Instead the above code have to return only those rows related to that chat instance.

So I think you forgot to put necessary where before returning the query builder.

   const query = new QueryBuilder(this.constructor, connection)
    query.collection = collection
    query.where(this.foreignKey, this.$primaryKeyValue) // the absence of this line will return all documents on pivot collection
    return query

I had to figure it out myself with my query. Am I missing something?