Utilize the composite primary key of an Entity within Typeorm for efficient data retrieval

I am working with the following database entities:

@Entity()
class Team {
  @PrimaryGeneratedColumn()
  id: string

  @PrimaryColumn()
  teamName: string

  @OneToMany(() => Player, player => player.team)
  players: Player[]
}

@Entity()
class Player {
  @PrimaryGeneratedColumn()
  id: string

  @ManyToOne(() => Team)
  team: Team
}

While using Typeorm, I encountered an error regarding foreign key implementation. It seems that the issue stems from the fact that the Player entity is trying to reference a composite primary key in Team instead of just the id. One solution would be to change the primary key structure in Team, but I am curious if there are other approaches to tackle this problem. I attempted the following modification without success:

@Entity()
class Player {
  @PrimaryGeneratedColumn()
  id: string

  @ManyToOne(() => Team)
  @JoinColumn([
    {name: 'teamId', referencedColumnName: 'id'},
    {name: 'teamName', referencedColumnName: 'teamName'}
  ])
  team: Team
}


Answer №1

I've had some challenges with using composite keys in TypeORM. Can you clarify why groupName is added to the primary key even when there is an auto-generated unique id present? Wouldn't it be more efficient to have a straightforward primary key on id and only use a unique constraint for groupName?

@Entity()
class Group {
  @PrimaryGeneratedColumn()
  id: string

  @Column({ unique: true })
  groupName: string

  @OneToMany(() => User, user => user.group)
  user: User[]
}

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

The attribute 'name' cannot be found within the class 'MyComponent'

I'm a beginner in Angular2 and I have no previous knowledge of version 1. Can you help me understand why this error is occurring and guide me on how to fix it? import { Component } from 'angular2/core'; @Component ({ selector: 'my- ...

What is the proper way to update a dropdown value in a React JS component?

Can you please guide me on how to assign a value in a dropdown in react js? I am retrieving the dropdown data after a delay of 3000 milliseconds and then I need to set a value in the dropdown. const App = ({ children }) => { const val = "ax"; const ...

Tips for incorporating animated features into a bar graph using jQuery

How can I create a dynamic animated bar graph using jQuery? I am looking to make the bar slide up from the bottom, incorporating images for both the bar and background. I have already set the positioning in CSS and now need to add animation to make the bar ...

React: Updating a state before calling another function - Best practices

In my code, there is a state variable named list that gets updated whenever the function setList is called. The setting of the list happens within the function AddToList, where a new value is added to the existing values in the list. However, I have notice ...

Creating visual content on a website

I'm currently working on a project where I need to showcase the results of a numerical model I am operating. My goal is to gather user input in the form of latitude/longitude coordinates, utilize php (or a similar tool) to trigger a python script that ...

repeating the identical content in the same setting

I am encountering an issue with jquery as I have 2 different sets of icons, each of which I want to do the same thing: My primary codes are <ul> <li> <a href=""> <i class="fa fa-facebook"></i> ...

Convenient Method for Making POST Requests with the Node Request Module and Callback

Does the .post() convenience method in Javascript/Node's request module accept a callback? I'm confused why it would be throwing an error like this: var request = require('request'); request.post({url: 'https://identity.api.foo/v ...

Tips for Keeping a Responsive Image at the Forefront of a Text-Image Layout as You Scroll

I'm currently in the process of creating a website where text appears on the left side with an accompanying image on the right. The challenge I'm encountering is ensuring that as users scroll, the image adjusts dynamically based on the associated ...

JavaScript regular expression for detecting valid characters without repeating a specific character

let rx = /(\/MxML\/[a-z0-9\[\]@/]*)/gi; let s = 'If (/MxML/trades[1]/value== 1 then /MxML/trades[type=2]/value must be /MxML/stream/pre/reference@href'; let m; let res = []; while ((m = rx.exec(s))) { res.push(m[1]); ...

Prefer using Android bulk insertion or updating over insertOrReplace

My Challenge: Currently, I am developing an Android application that utilizes SQLite to fetch and store data from a server. The process involves receiving a list from the server, iterating over it, and individually inserting each record into the DB. Howev ...

Is it possible for TypeScript to automatically determine the type of an imported module based on its path?

I'm currently working on creating a function, test.isolated(), which wraps around jest.isolateModules. This function takes an array of strings representing the modules to be imported, along with the usual arguments (name, fn, timeout), and then inject ...

What are the steps to modify an Azure SQL Database with pyodbc/odbc?

I have developed a Python script that scrapes data from a website and stores it in a Microsoft Access database. Now, I am looking to rerun the script but instead, I want to store the results in an Azure SQL database. However, I am encountering a persistent ...

The attribute 'disabled' is originally defined as a characteristic within the class 'CanColor & CanDisableRipple & HasTabIndex & MatChipBase'. However, it is replaced in the current context of 'MatChip' as an attribute

After updating my Angular version from 9.1 to 11, I encountered a compilation error. Error: node_modules/@angular/material/chips/chips.d.ts:120:9 - error TS2611:'disabled' is defined as a property in class 'CanColor & CanDisableRipple &a ...

Only display PHP page content if accessed through an AJAX request, not through directly typing the URL into the address bar

Is there a way to verify if a PHP page has been accessed via an Ajax request? I'm working on a page that displays a form for updating some database data (update.php), but I only want it to be accessible if it is called by a specific page named "change ...

Tips for populating a dictionary with a large datalist of around 2000 items

Currently, I'm facing an issue where the code I'm using takes about 10 seconds to run on Chrome and around 2 minutes on IE11, which is the primary browser it will be used with. for (var key in dict) { if (dict.hasOwnProperty(key)) { ...

Using Javascript to Divide Table into Separate Tables each Containing a Single Row

Is there a way to divide the content of this table into three separate tables using JavaScript? It is important that each table retains its header information. Unfortunately, I am unable to modify the id's or classes as they are automatically generat ...

Finding out whether the current date falls between a startDate and endDate within a nested object in mongoose can be done by using a specific method

My data structure includes a nested object as shown: votingPeriod: {startDate: ISOdate(), endDate: ISOdate()}. Despite using the query below, I am getting an empty object back from my MongoDB. const organizations = await this.organizationRepository.find( ...

Achieving multiple validations on a single element in AngularJS, along with the ability to validate

Currently, I am in the process of constructing a form and utilizing the built-in AngularJS validation objects to validate the form. The following is an overview of my form: <form name="myForm" ng-submit="DoSomething()" novalidate> <te ...

Utilizing JSON format for processing HTTP requests in JavaScript with Node.js

I'm working with a snippet that retrieves data in JSON format, but I'm interested in manipulating the data instead of just outputting it to the console. var request = require('request'); var headers = { 'Connection': ' ...

The div element with the id "wrapper" is not functioning properly within the box model

I have defined an ID wrapper in CSS: #wrapper { position: relative; background: yellow; -webkit-box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.2); box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.2); width: 960px; padding: 40px 35px 35px ...