question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Load relation ids without joining target entity

See original GitHub issue

tl;dr what’s the best way to fetch relation ids from a join table?

I have a data model that is unfortunately spread out across several databases, so I need to handle some relations manually with separate queries on other connections. What I’m trying to do is find a way to fetch relation ids from a join table only; typeorm adds an additional join to the related class’s table, which in my case, exists in another database.

// Database A
@Entity('usr')
class User {
  @PrimaryGeneratedColumn()
  public id: number;

  @Column()
  public name: string;
}

// Database B
@Entity()
class Article {
  @PrimaryGeneratedColumn()
  public id: number;

  @ManyToMany(() => User)
  @JoinTable({name: 'article_authorship', inverseJoinColumn: {name: 'author_id'}})
  public authors: User[] = [];

  public authorIds: number[] = [];
}

The article_authorship join table is also on Database B and looks like:

   Column   |  Type   | Modifiers
------------+---------+-----------
 article_id | bigint  | not null
 author_id  | bigint  | not null
 ordinal    | integer | not null

I’ve tried a few different things in my controller to populate Article#authors or Article#authorIds with data, or otherwise obtain an array of ids from that join table.

SelectQueryBuilder#innerJoinAndMapMany

const articles = articleRepository.createQueryBuilder('article');

articles.innerJoinAndMapMany('article.authorIds', 'article_authorship', 'authorship', 'article.id = authorship.article_id');

This almost works. The following query is executed:

SELECT "article"."id" AS "article_id", "article"."headline" AS "article_headline", "article"."content" AS "article_content", "authorship"."article_id" AS "authorship_article_id", "authorship"."author_id" AS "authorship_author_id" FROM "article" "article" INNER JOIN "article_authorship" "authorship" ON "article"."id" = authorship.article_id WHERE ("article"."date_deleted" IS NULL) AND "article"."id" IN ($1) -- PARAMETERS: ["41255"]

For an Article with 2 authors, this does in fact load 2 records with each User id; I can see that in the raw results from SelectQueryBuilder#getRawAndEntities. However, in the single entity that’s returned, Article#authorIds is still empty. The transformation from raw results to entities leaves that out.

SelectQueryBuilder#loadAllRelationIds

const articles = articleRepository.createQueryBuilder('article');

articles.loadAllRelationIds();

This results in the following query:

SELECT "article_authors_relation_id"."author_id" AS "author_id", "article_authors_relation_id"."article_id" AS "article_id" FROM "usr" "usr" INNER JOIN "article_authorship" "article_authors_relation_id" ON ("article_authors_relation_id"."article_id" = $1 AND "article_authors_relation_id"."author_id" = "usr"."id") ORDER BY "article_authors_relation_id"."author_id" ASC, "article_authors_relation_id"."article_id" ASC -- PARAMETERS: ["41255"]

Obviously, this fails outright, as the usr table is on Database A. I also attempted to use SelectQueryBuilder#loadRelationIdAndMap) and heavily modify the query but no luck there.

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:5 (4 by maintainers)

github_iconTop GitHub Comments

10reactions
pleerockcommented, Jul 21, 2017

Do you simply want to load ids from junction (many-to-many) table, right?

    @ManyToMany(type => Post, post => post.categories)
    posts: Post[];

    @RelationId((category: Category) => category.posts)
    postIds: number[];

See examples here.

0reactions
pleerockcommented, Oct 17, 2017

Closing as no answer from reportee. Btw, cross-database requests are supported now. You can find docs here.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Getting only ID from entity relations without fetching whole ...
I have a use case where I want to get food_group_id of an entity without getting full parent object from database. Using fetch="LAZY"...
Read more >
Relationship Loading Techniques
Joined eager loading is the most fundamental style of eager loading in the ORM. It works by connecting a JOIN (by default a...
Read more >
One-to-one relations - typeorm - GitBook
One-to-one is a relation where A contains only one instance of B, and B contains only one instance of A. Let's take for...
Read more >
Best Practices for Many-To-One and One ... - Thorben Janssen
I know, mapped to-many associations are useful, especially when you want to join entities in a JPQL query. But Hibernate loads all associated...
Read more >
TypeORM - Relations - Tutorialspoint
one-to-one − One object of the given entity relates to only one object of the target entity and vice versa. For example, a...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found