Search code examples
sqlruby-on-railstypeorm

Relations Has Many Through with 3 models - TypeORM


I have three models: User, Category and Feed.

The first one is User and it has a One to Many relationship with the second model which is Category. Category has a userId column and a Many to One relationship with User.

Category has a One To Many relationship with the third and last model: Feed. Similarly, Feed has a column categoryId and a Many To One relationship with Category.

I want to access the Feeds of a certain categoryId (for example of categoryId = 2) but only where the userId on this category is a certain value too (for example of userId = 1).

This relation is the has_many_through for Ruby on Rails programmers...

How can I build this query using TypeORM ? Alternatively, if you have an idea on how to write it in pure SQL I'll take it too.

I'm also thinking about creating a column userId directly through Feeds to have a One To Many relationship between User and Feed. Do you think it'll be more optimized to do so ?

Many thanks.


Solution

  • This is how you would achieve that through pure SQL, I'm not much help on the TypeORM front unfortunately.

    SELECT f.*
    FROM Feeds f
    LEFT JOIN Category g
    ON f.categoryId = g.categoryId
    WHERE f.categoryId = 2
    AND g.userId = 1