Understanding how to access a referenced relation field in TypeORM without having to load the entire entity

When establishing a ManyToOne/OneToMany relation, we are required to use @ManyToOne/@OneToMany decorators on a field.

In the context of my project, I have defined two entities: Project and Position.

This is how the relation was set up:

@Entity('positions')
export class Position {

  @ManyToOne(() => Project, {
    nullable: false,
    eager: true,
  })
  @JoinColumn()
  project: Project;

}

The TypeORM documentation states that this code will generate a projectId FOREIGN KEY column in the database to store the project id.

Now, when attempting to access the project property, TypeORM loads the corresponding project based on the id stored in the projectId field.

QUERY

Is there a way to retrieve the value of the pojectId field without loading the relational entity?

By default, the projectId property does not exist within the Position entity. Even if manually created, it remains unpopulated with the value from the projectId column.

I attempted to approach it using the following method:

  @ManyToOne(() => Project, {
    nullable: false,
    eager: false,
  })
  @JoinColumn()
  project: Project;

  projectId: string;

Answer №1

To access the relationship ID, you can utilize the @RelationId decorator provided by typeorm. Here is how you can implement this in your code:

import {
  Column,
  Entity,
  ManyToOne,
  RelationId,
  JoinColumn,
} from 'typeorm'

@Entity()
export class Position {
  @ManyToOne(() => Project, {
    nullable: false,
    eager: false,
  })
  @JoinColumn()
  project: Project;

  @Column()
  @RelationId((position: Position) => position.project)
  projectId: string;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

choose 5 specific days out of the week

I have a database table named "Lineas" with columns (id, date, project_id, hours). My goal is to calculate the total number of hours for each day within a week. For instance, I want the output to display the sum of hours for dates ranging from 01/01/2013 t ...

Expanding the capabilities of HTML anchor tag elements with React and TypeScript

In my React project using TypeScript, I am encountering an issue with accessing the properties of an link element compared to an a element. Whenever I try to use the properties of a link tag with an a tag, it results in an error. Is there a specific &apos ...

In TypeScript and React, what is the appropriate type to retrieve the ID of a div when clicked?

I am facing an issue in finding the appropriate type for the onClick event that will help me retrieve the id of the clicked div. const getColor = (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => { const color = event.target.id; // ...

Creating a VB.NET Webforms application allows for the seamless sharing of global variables between code and SQL

I've been tasked with updating some legacy webforms applications. Currently, we store client information in a global variables class like the one below: Public Class globals Enum Enterprise Enterprise1 = 10 Enterprise2 = 11 ...

Having trouble selecting checkboxes in React Native

When working on React Native tests, I utilize react-native-paper. Below is the code snippet: {(!props.question.isSingleAnswer && props.question.answers.length) && <View> {props.question.answers.map((item) => ( ...

Show all corresponding values instead of just the initial one

I have a created a query to generate reports by fetching data from multiple tables. However, I am faced with a challenge in echoing more than one matching value from a specific table. For instance, in the vtiger_addisa table, there are multiple newcurren ...

Mapping nested JSON to model in Angular2 - handling multiple API requests

Having trouble integrating two HTTP API Responses into my Model in Angular 2. The first API Call returns data like so: [{ "id": 410, "name": "Test customdata test", "layer": [79,94] }, { "id": 411, "name": "Test customdata test2", ...

SQL Query alias option

select b.test_id,d.test_id from test b, test d Considering the query above, what will be the outcome? Will both columns display the same results or different results? ...

Sorting an object array by date is causing a problem

UPDATE: Finally cracked the code on this issue. I initially assumed that Date was interpreting the date ("29-04-2020") as DD-MM-YYYY, when it should actually be MM-DD-YYYY. For instance, here's an object array I'm working with: let t ...

Tips for choosing a join based on two criteria for a single column

I am attempting to achieve a specific output in my query. id tag name 1 foo name 1 bar name 2 foo name 2 foss name My current approach is as follows: select id, group_concat(distinct tag) as tag, group_concat(distinct name) as name ...

Enabling cookie communication between NestJS server and Next.js frontend

I seem to be encountering challenges when trying to set cookies from a NestJS backend into my Next.js app. My NestJS application is running on port 3001 and here is my bootstrap setup: async function bootstrap() { const app = await NestFactory.create(Ap ...

Question on design: Filtering attributes with SQL

I am facing a dilemma with my database tables - Operation and Equipment. Each operation requires a specific set of attributes, but the logic behind assigning these attributes varies: Operation Foo needs equipment A and B Operation Bar doesn't requir ...

What is the best approach for declaring helper functions and constants within nest.js?

Currently, I am delving into the world of nest.js and building an API using it. However, I have hit a roadblock when it comes to defining constants and helper functions. Like many APIs, some of my endpoints require pagination, and I want to set a default ...

What is the best method for extracting data from JSON and converting it into the SUPER data type

I need to extract data from a JSON object with a date type of SUPER. The reason for defining the data type as SUPER is because the size of the data exceeds what can be stored in a VARCHAR. I attempted to use JSON_EXTRACT_PATH_TEXT and JSON_EXTRACT_ARRAY_E ...

Function parameter constrained to a specific property of a generic type T

In my codebase, I have a custom function called uniqBy, which filters out duplicate items based on a specified key: export function uniqBy<T>(array: T[], key: any): T[] { const seen = {}; return array.filter(function (item) { if (item ...

Fixing the Bootstrap 4 issue "Popper.js required for Bootstrap dropdowns" using Aurelia CLI and Require.js

Struggling to set up Bootstrap 4 beta in an Aurelia CLI app (v0.31.1) with requirejs and TypeScript. Despite trying different configurations, the console consistently shows this error: Uncaught Error: Bootstrap dropdown require Popper.js Here's a ...

Currently retrieving partition id from the table

Check out the new table partitioning feature in OpenEdge 11.4: knowledgebase.progress.com/articles/Article/P58968 select "_index-name" from PUB."_index" idx, PUB."_file" fi where fi."_file-name" = 'Customer' and **idx.rowid** = (select"_ ...

What is the priority of the exact phrase in SQLite FTS?

Imagine the scenario where the search input is 'what is'. This query will return results that include both 'whatever it is' and 'what is' as an exact phrase. However, how can I ensure that the exact phrase appears first in the ...

Locate the closest point among a set of coordinates to a specified point

I have a situation where I have an object that contains latitude and longitude attributes. My goal is to find the closest match in an array of similar objects by considering both latitude and longitude. obj = {latitude: 55.87, longitude: 4.20} [ { & ...

SQL Conditional Boolean Logic Statements

I don't quite understand the reasoning behind this statement. When the type is labeled as 'rare', the price should be above $500. Although this condition is satisfied, I'm unclear on how it works. CHECK (type != 'rare' OR p ...