herbsjs / herbs2knex

Create repositories using Knex to retrieve and store Entities
Other
7 stars 13 forks source link

Insert - Entity with 1:1 relationships with other entity #57

Open dalssoft opened 2 years ago

dalssoft commented 2 years ago

Given:

const User =
        entity('User', {
          id: id(Number),
          description: field(String),
        })

const Customer =
        entity('Customer', {
          id: id(Number),
          description: field(String),
          user: field(User)   // <---- relationship 1:1
        })

class CustomerRepository extends Repository {
    constructor(injection) {
        super({
            entity: Customer,
            table: "customer",
            knex: connection,
            foreignKeys: [{ userId: String }], // <---- relationship 1:1 on DB
        })
    }
}

when:

const customer = Customer.fromJSON({ id: 1, description: "C1", user: { id: 2 } })
const repo = new CustomerRepository()
const ret = await repo.insert(customer)

it should insert not only the fields for customer table (id and description) but also user_id

danielsous commented 2 years ago

I will act on it.