How to handle inverse of manyThrough relationship?

How would you recommend handling the inverse of manyThrough relationship? Ideally, there would be a belongsThrough relationship but I’m guessing it doesn’t exist for a reason so I appreciate any feedback.

Use case example: User -> Projects -> Tasks

Related question: would it fine to have a task belongTo both a User and a Project or is that some sort of violation of best practices (i.e. since you have to always guarantee task_user_id === project_user_id).

1 Like

Gone through this http://adonisjs.com/docs/4.0/relationships#_many_through ?

I’m confused, there’s nothing there about handling the inverse of manyThrouh

1 Like

Maybe you should try explaining what you want to achieve.

@alidcastano Did you ever get a response to your “BelongsToThrough” question?

I have this same type of relationship that I’d like to reflect in my model.

Tables:
Applications - id, product_account_id
ProductAccounts - id, product_id
Products - id

So, starting on the Product side, the Product would have a “hasMany” relationship to ProductAccount, and a “manyThrough” relationship to Application.

ProductAccount would have a “belongsTo” relationship to Product, and a “hasOne” relationship to Application.

Now, coming at it from the Application side, the Application would have a “belongsTo” relationship to ProductAccount. How do I define the Application’s relationship to the Product?

I think developers should not limit themselves to the abstractions provided by Lucid/Knex. If you observe any limitations, you can easily go raw with your SQL queries.

Hi @alidcastano

It may be a little late but is it possible using the same manyThrow relationship.

According to the documentation https://adonisjs.com/docs/4.1/relationships#_many_through:

manyThrough(
  relatedModel,
  relatedMethod,
  primaryKey,
  foreignKey
)

In the example Countries hasMany Users and they have many Posts. All you have to do in the Post is to change primaryKey for foreignKey

Posts.js

country(){
return this.manyThrow(
‘Users’,
‘country’,
‘country_id’,
‘id’
}

The only problem you have in this way is that you will get an array with the country instead of a single value.

the alternative is to use .with(‘user.country’)

Hope this helps for future developments.

B/R