Relations when entity belongs to same entity twice (JS-Data)

102 Views Asked by At

Imagine a Sales Order model, like this:

create table sales_orders(
  id int primary key,
  order_date date,
  customer_party_id int not null references parties,
  sales_party_id int not null references parties
);

create table parties (
  id int primary key,
  type text check (type in 'individuals', 'organizations'),
  given_name text,
  surname text,
  org_name text
);

How to model JSData Relations in this case?

Obvious, I cannot do this:

store.defineMapper("sales_orders", {
    relations:{
        belongsTo:{
            parties:{
                foreignKey:"customer_party_id",
                localField:"customer_party"
            },
            parties:{
                foreignKey:"sales_party_id",
                localField:"sales_party"
            }
        }
    }
});

I can rename one of the belongsTo fields, and that works on read, but not on write...(using JSONAPI adapter)

2

There are 2 best solutions below

1
Justin Grant On

I don't know if this counts as an answer, but it's the only place I can put code. :) I'm not clear what's consuming the object you're sending but I would expect you to be able pass your parties as an array like the following:

store.defineMapper("sales_orders", {
relations:{
    belongsTo:{
        parties:[{
            foreignKey:"customer_party_id",
            localField:"customer_party"
        },
        {
            foreignKey:"sales_party_id",
            localField:"sales_party"
        }]
    }
}

});

Is this an option?

0
Tch On

ok so why do you want two foreign keys when you have type on your parties table to distinct customer from sale? unless this column is for something else, so then you can just create one more ex. party_type for that purpose.

I would suggest you delete one of the columns, rename the remaining one to party_id and then you should defineMapper for both tables like this

store.defineMapper('parties', {
    relations: {
        hasMany: {
            sales_orders: {
                foreignKey: 'party_id',
                localField: 'party'
            }
        }
    }
});
store.defineMapper('sales_orders', {
    relations: {
        belongsTo: {
            parties: {
                foreignKey: 'party_id',
                localField: 'party'
            }
        }
    }
});