typeorm icon indicating copy to clipboard operation
typeorm copied to clipboard

Cascade insert one to many not working

Open FrankMathers opened this issue 6 years ago • 14 comments
trafficstars

Issue type:

[X] question [X] bug report [ ] feature request [ ] documentation issue

Database system/driver:

[ ] cordova [ ] mongodb [ ] mssql [ ] mysql / mariadb [ ] oracle [X] postgres [ ] cockroachdb [ ] sqlite [ ] sqljs [ ] react-native [ ] expo

TypeORM version:

[X] latest [ ] @next [ ] 0.x.x (or put your version here)

Steps to reproduce or a small repository showing the problem:

import {Entity, PrimaryGeneratedColumn, Column, OneToOne, JoinColumn,CreateDateColumn, UpdateDateColumn, Timestamp, OneToMany} from "typeorm";
import {Profile} from "./profile";
import {Job} from "./job"

@Entity()
export class User {

    @PrimaryGeneratedColumn("uuid")
    public  id: string;

    @Column()
    public  name: string;

    @OneToOne(type => Profile, {cascade: true})
    @JoinColumn()
    public profile: Profile;

    @OneToMany(type => Job, job => job.user , {cascade: true})
    public job: Job[];

    @CreateDateColumn()
    public CreatedAt: Timestamp;

    @UpdateDateColumn()
    public UpdatedAt: Timestamp;
}
import {Entity, PrimaryGeneratedColumn, Column,CreateDateColumn, UpdateDateColumn, Timestamp, ManyToOne, OneToMany} from "typeorm";
import { User } from "./user";

export enum JobStatus {
    CLOSED = "closed",
    OPEN = "open",
    NEW = "new"
}

@Entity()
export class Job {

    @PrimaryGeneratedColumn("uuid")
    public id: string;

    @Column()
    public description: string;

    @Column()
    public State: JobStatus;

    @ManyToOne(type => User, user => user.job,{onDelete:'CASCADE'})
    public user: User;
    
    @CreateDateColumn()
    public CreatedAt: Timestamp;

    @UpdateDateColumn()
    public UpdatedAt: Timestamp;
}

When Create User with multiple jobs, only last job saved into the database.

user = 
    {
        "name": "1",
        "profile": {
            "gender": "M",
            "description": "This is Chain"
        },
        "job": [
            {
                "description": "NEW",
                "State": "NEW"
            },
            {
                "description": "OPEN",
                "State": "OPEN"
            }
        ]
    }

const addUser = async (user: User) => {
  const connection = getConnection();
  return connection.manager.save(user)
}

and return value is

{
    "name": "1",
    "profile": {
        "gender": "M",
        "description": "This is Chain",
        "id": "d09d76fd-1efc-4e3a-9aeb-f1b4eb5212d6",
        "CreatedAt": "2019-03-20T09:11:18.720Z",
        "UpdatedAt": "2019-03-20T09:11:18.720Z"
    },
    "job": [
        {
            "description": "OPEN",
            "State": "OPEN",
            "id": "0672b671-1d82-4ea1-89ec-ee3065b6529e",
            "CreatedAt": "2019-03-20T09:11:18.720Z",
            "UpdatedAt": "2019-03-20T09:11:18.720Z"
        },
        {
            "description": "OPEN",
            "State": "OPEN",
            "id": "0672b671-1d82-4ea1-89ec-ee3065b6529e",
            "CreatedAt": "2019-03-20T09:11:18.720Z",
            "UpdatedAt": "2019-03-20T09:11:18.720Z"
        }
    ],
    "id": "3b81d407-b58f-4471-a59c-fb9e50504d80",
    "CreatedAt": "2019-03-20T09:11:18.720Z",
    "UpdatedAt": "2019-03-20T09:11:18.720Z"
}

FrankMathers avatar Mar 20 '19 10:03 FrankMathers

Currently facing the same problem. Master

export class Transaction {
  @PrimaryGeneratedColumn('rowid')
  id: number;

  @Column({ type: 'real', precision: 3, nullable: false })
  price: number;

  @Column({ type: 'real', precision: 3, nullable: false })
  paid: number;

  @Column('datetime')
  timestamp: Date;

  @OneToMany(
    type => TransactionItem,
    item => item.transaction,
    { eager: true, cascade: true }
  )
  items: TransactionItem[];

  @Column({ enum: PaymentMethod })
  paymentMethod: PaymentMethod;
}

Slave

export class TransactionItem {
  @PrimaryGeneratedColumn('rowid')
  id: number;

  @ManyToOne(
    type => Transaction,
    transaction => transaction.items,
    { nullable: false }
  )
  transaction: Transaction;

  @ManyToOne(type => Product, { cascade: true })
  @JoinColumn()
  product: Product;

  @Column('int')
  qty: number;
}

SimantoR avatar Feb 15 '20 22:02 SimantoR

before line "return connection.manager.save(user)" use the connection.manager.create(User,user).. and then save the returned object.. this resolved for me 👍

mottajunior avatar Feb 28 '20 16:02 mottajunior

Could you solve it? I have a similar problem but using Mysql.

alanscordoba avatar Oct 31 '20 02:10 alanscordoba

I found that in order to cascade one to many, lazy load has to be set to false.

Of course it does..

JohnnyClutch avatar Nov 01 '21 19:11 JohnnyClutch

I have the same problem :/

CodingByJerez avatar Dec 24 '21 08:12 CodingByJerez

I have the same problem too in the react native app using the expo sqlite, but it works in dev env. And it's really weird.

nikitincryoocyte avatar Jan 14 '22 08:01 nikitincryoocyte

I have the same problem

bekkazy-k avatar Jan 21 '22 10:01 bekkazy-k

@JohnnyClutch could you please elaborate a little? What should be disabled and where? I do not see any lazy loading in my code. This is actually an eager: true relation...

Pipeliner avatar Jun 30 '22 15:06 Pipeliner

I'm using the EntitySchema-in-a-separate-file approach, and there is a lazy property associated with the relations array elements.

It's been a while, so I don't remember the why. Sorry.

JohnnyClutch avatar Jun 30 '22 18:06 JohnnyClutch

Can confirm this is not working for us.

bombillazo avatar Jul 29 '22 20:07 bombillazo

Is this issue resolved yet? In my case it's only saving the first object from the array

deniscitaku avatar Sep 29 '22 08:09 deniscitaku

Debugging this problem I changed the cascade to manual insertion, and turned on typeorm's debugging flag.

Cascade was not working, parent table got correctly inserted, but children records didn't.

I noticed that there was a mismatch error between sql table's column properties and class' properties metadata. I corrected this and worked again, but I won't enable cascade again. It seems unstable to me. Typeorm should have forwarded the error.

RonaldPaguay avatar Jul 25 '23 21:07 RonaldPaguay