dfahlander / dexie-relationships

Dexie relationship plugin
MIT License
89 stars 17 forks source link

Relationships based on Object #35

Closed Son-kun closed 4 years ago

Son-kun commented 4 years ago

Hi, currently creating relations requires explicit ID in parent object (if I understand corretly based on docs/tutorials). There will be possibility to create relations based stricte on object? E.g.

class FooA {
    id?: number;
    someParam: string;
    otherParam: FooB;
}

class FooB {
    id?: number;
    someOtherParam: string;
}

class MyDB extend Dexie {
    ...
    constructor() {
        ...
        this.version(1).stores(
            fooA: '++id, someParam, otherParam -> otherParam.id',
            fooB: '++id, someOtherParam'
        );
        ...
    }
}

Currently after try to save FooA object I get in indexedDB row with full data (json) of FooA and FooB, but I want to have only ID of FooB in FooA.

dfahlander commented 4 years ago

The right-part of the arrow should point to <table>.<id-prop>, not <prop>.<otherProp>. You should also distinguish the foreign key prop from the virtually optionally included prop.

class FooA {
    id?: number;
    someParam: string;
    otherProp?: FooB;
    otherPropId: number;
}

class FooB {
    id?: number;
    someOtherParam: string;
}

class MyDB extend Dexie {
    ...
    constructor() {
        ...
        this.version(1).stores(
            fooA: '++id, someParam, otherPropId -> fooB.id',
            fooB: '++id, someOtherParam'
        );
        ...
    }
}

Then using with() wont make otherProp overwrite otherPropId. Notice that the optionally included otherProp will not be enumerable - which means it wont appear Object.keys() or when doing JSON.stringify(). The rationale of that is that you should be able to put() the object back without having to delete the prop first.

const foos = await db.fooA.with({otherProp: 'otherPropId'});
Son-kun commented 4 years ago

Ok, it's work, thanks.