typeorm / typeorm

ORM for TypeScript and JavaScript. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.
http://typeorm.io
MIT License
33.99k stars 6.26k forks source link

Problem when cascading update - SQLITE_CONSTRAINT: NOT NULL constraint failed: customer_address.customer_id #212

Closed natanielkdias closed 7 years ago

natanielkdias commented 7 years ago

Hi, I'm having an issue when I try to persist an object which has an array to save together.

Below, Here is my entity structure:

@Table('order')
export class Order {

    @PrimaryGeneratedColumn()
    id: number;

    @ManyToOne(type => Customer, customer => customer.id, { cascadeAll: true, nullable: false })
    @JoinColumn({ name: 'customer_id' })
    customer: Customer;
}

@Table('customer')
export class Customer {

    @PrimaryGeneratedColumn()
    id: number;

    @Column("string", { length: 50, nullable: true })
    name: string;

    @OneToMany(type => CustomerAddress, address => address.customer, { cascadeAll: true, nullable: false })
    addresses: Promise<CustomerAddress[]>;
}

@Table('customer_address')
export class CustomerAddress {

    @PrimaryGeneratedColumn()
    id: number;

    @Column("string", { length: 100, nullable: true })
    address: string;

    @ManyToOne(type => Customer, customer => customer.addresses, { nullable: false })
    @JoinColumn({ name: 'customer_id' })
    customer: Promise<Customer>;
}

Here is my persist method:

create(phoneNumber: string): Promise<Order> {
    return this.connectionService.get().then(async connection => {

        let customer = new Customer();
        let address = new CustomerAddress();
        address.customer = Promise.resolve(customer);        
        customer.addresses  = Promise.resolve([new CustomerAddress()]);

        let order = new Order();
        order.customer = customer; 

        return await connection.entityManager.persist(order);

    });
}

And here is the error:

Error: SQLITE_CONSTRAINT: NOT NULL constraint failed: customer_address.customer_id
    at Error (native)

May someone help me please? Thanks in advance.

pleerock commented 7 years ago

I guess this is because you are using nullable: true in your relations. Don't use this in relations because it can bring problems during persistence of the complex object graphs.

pleerock commented 7 years ago

have you resolve your issue?

natanielkdias commented 7 years ago

Hi,

Sorry for being late. But yes I solved it. But now I'm having that issue on other situation. When I remove some item on a "@OneToMany" array the error is thrown, The type orm try to set null on the foreign key field. Is there some configuration to delete this orphan item instead of set null?

pleerock commented 7 years ago

Please create a separate issue with detailed description of your issue.