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.

How to properly create a select query when using a (custom) junction table

See original GitHub issue

This is a question regarding the proper way to select a record based on properties from both models (who share the junction table).

For example, let’s say we have the following two models:

@Entity({ name: "users" })
class User extends BaseEntity {
	@PrimaryColumn()
	public id: string;
	
	@OneToMany(type => RecordContext, context => context.user)
	public contexts: RecordContext[];

	// more columns
}

@Entity({ name: "records" })
class Record extends BaseEntity {
	@PrimaryColumn()
	public id: string;
	
	@OneToMany(type => RecordContext, context => context.record)
	public contexts: RecordContext[];

	// more columns
}

And this junction table:

@Entity({ name: "record_contexts" })
class RecordContext extends BaseEntity {
	@ManyToOne(type => Record, record => record.contexts, { primary: true })
	public readonly order: Order;

	@ManyToOne(type => User, user => user.contexts, { primary: true })
	public readonly user: User;

	@Column()
	public readonly role: string;

	@Column("simple-json")
	public readonly meta: any;
}

I want to be able to get the joined records for a specific record_id and user_id, and I’m stuck here:

Record.createQueryBuilder("record")
	.innerJoinAndSelect("record.contexts", "context")
	.where("record.id = :recordId", { recordId })
	.andWhere("context.user_id = :userId", { userId })

My problem is how to reference the user part the in the last line, since context.user is User and I don’t have the user_id column.
I’m using TypeORM version 0.1.12.

Thanks.

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:10 (9 by maintainers)

github_iconTop GitHub Comments

2reactions
pleerockcommented, Jun 19, 2018

I put answers in PR

0reactions
emiromcommented, Nov 1, 2019

Is it possible to query on typeORM junction tables? want to do a low complexity query on a many to many relations (todos-tags) using this query on todo_tags_tag junction table of typeORM with tagId and todoId FKs:

@Resolver(Todo)
export class TodoTagResolver {
  @FieldResolver(() => [Tag], { nullable: true })
  async Tags(@Root() todo: Todo): Promise<Tag[] | undefined> {
    const result = await getRepository(Tag).query(
      `SELECT * FROM tag
     INNER JOIN  todo_tags_tag ON tag.id=todo_tags_tag.tagId
     WHERE todoId=$1`,
      [todo.id]
    );
    console.log(result);
    return result;
  }
}

the respond is : "column todo_tags_tag.tagid does not exist",

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to SELECT query including a junction table
I need to create a SELECT statement that will return four columns: student_ID Firstname course_ID course_Name from two tables after enrollment.
Read more >
[Solved]-How to make query in junction table in a many-to ...
You can use group by and having : select mp.match_id from match_player mp where player_id in (1, 5, 9, 11, 23) group by...
Read more >
SQL JOIN TABLES: Working with Queries in SQL Server
In this article, you will see how to use different types of SQL JOIN tables queries to select data from two or more...
Read more >
Create a query based on multiple tables - Microsoft Support
Build a select query by using tables with a many-to-many relationship · On the Create tab, in the Queries group, click Query Design....
Read more >
Proper way to implement Junction Object from SQL tables
Then I created a list of all possible Attributes and gave each one an ID. Then I created an "Intermediate" table that held...
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