'TypeORM retrieve list of entities by array of IDs (Postgres)

I have a table of articles. Each article has a column named "categories_ids". This column is an array of IDs

I'd like TypeORM to retrieve the linked categories every time I retrieve a article, but it doesn't seem to work.

Here's my article entity :

import {
  Column,
  Entity,
  JoinColumn,
  ManyToOne,
} from 'typeorm';
import { Category } from '../categories/category.entity';

@Entity({ name: 'articles' })
export class Article {
  @Column({ name: 'title' })
  title: string;

  @Column('uuid', {
    name: 'categories_ids',
    array: true,
    default: '{}',
    nullable: false,
  })
  categoriesIds: string[];

  @ManyToOne(() => Category)
  @JoinColumn([{ name: 'categories_ids', referencedColumnName: 'id' }])
  categories: Category[];
}

Here is my category entity :

import { Column, Entity } from 'typeorm';


@Entity({ name: 'categories' })
export class Category {
  @Column({ name: 'title' })
  title: string;
}

I'd like to have a key named categories in the Article object that would hold all retrieved categories. A article can hold many categories IDs (which belong to many categories). A category could be hold by many articles but that's should not be possible to retrieve articles from a category.

Could you tell me where I am doing wrong ?

Best regards,



Solution 1:[1]

In my case instead of using ManyToOne I used ManyToMany relation for same type of entities.

Change your article entity like:

import {  Column,  Entity,  JoinColumn, ManyToMany } from 'typeorm';
import { Category } from '../categories/category.entity';

@Entity({ name: 'articles' })
export class Article {
  @Column({ name: 'title' })
  title: string;
    
  @ManyToMany(() => Category, area => area.id)
  @JoinTable()
  categoriesIds: Category[];
}

and your category entity like:

import { Column, Entity } from 'typeorm';
@Entity({ name: 'categories' })
export class Category {
  @Column({ name: 'title' })
  title: string;
}

Now during creating article must pass array of category ids like:

categoriesIds:[{id:1},{id:2}]

For your reference let suppose that request body coming like:

req.body = {
  title: 'Artical-1',
  categoriesIds: [1, 2]
}

and service code is like:

createArtical = (req, res) => {
    connection.then(async connection => {
        let newArticle = new Article();
        newArticle.title = req.body.title;
        newArticle.categoriesIds = req.body.categoriesIds.map((id) => ({ id }));
        let artical = await connection.manager.save(newArticle);
        res.send({ msg: "Artical created", artical: artical })
    }).catch(error => {
        res.send({ msg: "error", error: error })
    });
}

I think it is helpful for you.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ouflak