Relationship between multiple entities with a row representing the quantity involved

For one of my classes, I need to create a minimal database scenario. The task involves setting up a portfolio and storing the amount of coins within it.

So far, I've created tables for coins and portfolios. Each portfolio can contain multiple coins, and coins can belong to multiple portfolios, establishing a many-to-many relationship.

Now, the challenge is determining how to store the quantity of coins within each portfolio, considering that it varies for each one.

Do I need to create a third table with another many-to-many relationship? If so, what would this third table look like? Currently, our framework, mikro-orm, automatically generates a table called 'portfolio_coins' for the m:n relationship.

Here is an excerpt of my code:

Portfolio.ts

@Entity()
export class Portfolio extends BaseEntity {
   @Property()
   name: string;

   @ManyToOne(() => User, { nullable: true, cascade: [] })
   owner?: User;

   @ManyToMany(() => Coin)
   coins = new Collection<Coin>(this);

   constructor({ name, owner }: CreatePortfolioDTO) {
       super();
       this.name = name;
       this.owner = owner;
   }

Coin.ts

@Entity()
export class Coin {
   @PrimaryKey()
   id: string;

   @Property()
   name: string;

   @Property()
   symbol: string;

   @Property()
   rank: number;

   @Property()
   marketCapUsd: number;

   @Property()
   priceUsd: number;

   @ManyToMany(() => Portfolio, (portfolio) => portfolio.coins)
   portfolios = new Collection<Portfolio>(this);

   constructor({ id, name, symbol, rank, marketCapUsd, priceUsd}: CreateCoinDTO) {
      this.id = id;
       this.name = name;
       this.symbol = symbol;
       this.rank = rank;
       this.marketCapUsd = marketCapUsd;
       this.priceUsd = priceUsd;
   }

Although we are using typescript, I believe the implementation will not be affected once I have a clear plan. I hope my question is clear. Thank you in advance!

Answer №1

To effectively track the quantity of coins in a portfolio, creating a separate table is necessary. This eliminates the need for a ManyToMany relationship.

This table can be named PortfolioDetail. Both Portfolio and Coin will establish a OneToMany relationship with PortfolioDetail.

In addition to recording the portfolio and coin in the PortfolioDetail table, a third property must be included to monitor the quantity (or amount).

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 Hapi response fails to display JSON data in a nested tree format

Hey there! I've got this object with a specific structure. Here it is: interface FolderWithContent { uuid: string name: string; folders: Array<FolderWithContent>; files: Array<Files>; } Just a heads up, Files is an extens ...

Is there a way to apply a decorator to a function that has been returned?

Can the following be accomplished? bar () { @custom yield () => { } } ...

Transformer Class: An object containing properties that are instances of another class

class ClassA { x: number; y: number; sum(): number { return this.x + this.y; } } class ClassB { @Type(() => ClassA) z: {[key: string]: ClassA}; } const b = transformObject(ClassB, obj); const z = b.z[key]; const s = z.s ...

Utilize a function to wrap the setup and teardown code in Jest

I am attempting to streamline some common setup and teardown code within a function as shown below: export function testWithModalLifecycle() { beforeEach(() => { const modalRootDom = document.createElement('div') modalRootDom.id = M ...

Trapped in the Google Maps labyrinth (Angular)

Hey there everyone! I'm currently working on an exciting angular application that integrates the Google Maps API. The goal is to create a feature that shows the 20 closest coffee shops based on the user's current location. However, I seem to be r ...

Exploring the concept of the never type in TypeScript 2

Exploring the latest features in TypeScript 2.0, I came across the never type. It appears to be a clever method for defining the type of functions that do not have a return value. If I understand correctly, the never type can be assigned to any other type ...

Troubleshooting Problem with Installing Angular2-Google-Maps Component in FountainJS Application

Using the FountainJS Angular2 generator with Typescript and Systems.js has been helpful for scaffolding my project. Check it out here However, I encountered an issue while trying to add a component to the project. Upon importing {GOOGLE_MAPS_DIRECTIVES}, ...

Ways to redirect to a different page following a successful execution of a mutation in React-query

I am facing an issue where a memory leak warning appears when I redirect to another page after a mutation. Despite trying various methods, I have not been able to find a solution. The specific warning message is: Warning: Can't perform a React state ...

TypeScript requires that when explicitly specifying the return type of a generator, the `Generator.prototype.return` function must accept

I am utilizing a generator function to serve as a consumer for accumulating strings: function *concatStrings(): Generator<void, string, string> { let result = ''; try { while (true) { const data = yield; result += data; ...

Utilizing interpolation in Angular to apply CSS styling to specific sections of a TypeScript variable

Suppose I have a variable called data in the app.component.ts file of type :string. In the app.component.html file, I am displaying the value of data on the UI using string interpolation like {{data}}. My question is, how can I apply some css to specific ...

On which platform is the getFeatureInfo request constructed using Cesium?

Currently, I am working with Cesium and Angular. I am trying to locate where the request URL is generated for GetFeatureInfo in Cesium, but unfortunately I am unable to find it. My goal is to display feature information when clicking on the map. However, ...

Typescript array iteration using dual parameters

I seem to be struggling with the logic behind this seemingly straightforward iteration question. My task involves iterating through an array of data based on id and code, removing data only when the code is not associated with the given id's. Let&ap ...

Guide on incorporating Paddle into your SvelteKit project

I'm struggling to implement a Paddle Inline Checkout in SvelteKit. Every time I try, I keep encountering the error message Name Paddle not found. It seems like the script is not functioning properly. Console Error: Uncaught (in promise) ReferenceErro ...

Create a TypeScript function that can be called and has an extended prototype definition

I am seeking to create a callable function foo() (without using the new operator) that will also include a property foo.bar(). The JavaScript implementation would be as follows: function foo() { // ... } foo.prototype.bar = function bar() { // .. ...

Getting event properties in a React component using the rest operator: A comprehensive guide

Can someone please assist me? I am new to TypeScript and struggling with how to use event props in my component. I have defined two props and need all my events as rest props. I encountered an error when trying to use my component with onClick event. The ...

The functionality of Angular 5 reactive form valueChanges is not functioning correctly

I am currently working with a form inside a service: this.settingsForm = this.formBuilder.group({ names: this.formBuilder.array([]), globalIDs: this.formBuilder.array([]), topics: this.formBuilder.array([]), emails: thi ...

Using an Object as a Key in Maps in Typescript

I had the intention of creating a Map object in Typescript where an object serves as the key and a number is the value. I attempted to define the map object in the following manner: myMap: Map<MyObj,number>; myObj: MyObj; However, when I tried to a ...

Using TypeScript to implement functional props in React applications

When passing functional props from a parent to a child component with typescript: import react, {Component} from 'react' import Child from './Child' //some type declaration class Parent extends Component<{IProps},{IState}> { stat ...

TypeORM's one-to-many relationship alters the primary entity once the relationship has been established

When working on my side project, I decided to implement a friend request system using NestJS + TypeORM for the backend. However, I encountered a peculiar issue where every time I tried to associate a Friend entity with a specific user, the target field of ...

The alignment of the first and second steps in Intro.js and Intro.js-react is off

There seems to be an issue here. Upon reloading, the initial step and pop-up appear in the upper left corner instead of the center, which is not what I anticipated based on the Intro.js official documentation. https://i.stack.imgur.com/ICiGt.png Further ...