Mazzy
Mazzy

Reputation: 14189

Does it have any sense using hasOne and belongsTo at the same time?

I have a scenario like the following:

Account.belongsTo(models.Address, {
    as: 'address',
    foreignKey: { name: 'addressId', field: 'address_id' },
    onDelete: 'RESTRICT'
});

Address.hasOne(models.Account, {
    as: 'account',
    foreignKey: { name: 'addressId', field: 'address_id' },
    onDelete: 'RESTRICT'
});

I don't get it if I should use them both or not. BelongsTo probably yes but it's necessary to use also hasOne?

Upvotes: 0

Views: 132

Answers (2)

syldor
syldor

Reputation: 1176

Doing both the definitions allows you to select the address of an account and the account of an address.

models.account.findAll({
  include: [{
    model: models.address
  }]
});

models.address.findAll({
  include: [{
    model: models.account
  }]
});

Upvotes: 1

cfogelberg
cfogelberg

Reputation: 1488

As a general rule: Yes, you should define both.

From a practical perspective, you should define the association for a model Foo if you ever need to call the fooInstance.setBar and fooInstance.getBar methods on an instance. You should also define the association if you ever need to do Foo.find(..., { include: [Bar] });.

From a conceptual perspective, you should ask if it makes sense for the relationship to be bidirectional. If a Foo belongs to a Bar, does that mean that a Bar has one (or many) Foo's? Usually the answer to that question is going to be yes.

Upvotes: 2

Related Questions