1
votes

I'm actually confused about using either hasOne() or belongsTo() relationship. Assuming the relation is 1:1. Then which one?

  • An invoice hasOne a customer?
  • An invoice belongsTo a customer?

Noted that I've implemented both, and they works well .. But what's the standard one? When should I use which one?

4
Doesn’t the name of each imply that already, if you think about it …? gist.github.com/kaizerroll/22d887a6ee2bdf5aec2df3e4b499497e does a pretty good job of explaining it IMHO. What is source and what is target is the most important aspect here.CBroe
@CBroe Thank you for the link you provided.Martin AJ

4 Answers

0
votes

hasOne can be used in a strong model or entity

belongsTo can be used in a weak model or entity.

I am sure you have an idea of strong and weak entities in database.

0
votes

you can use invice hasOne(customer) in your case you can not use hasOne() with customer because customer has many invoices so batter use hasOne() with invoice and belongsTo() with customer. Ex. invoice model hasOne(customer)

while in customer model belongsTo(invoice)

0
votes

It depends on which table has the foreign key.

Imagine a relationship between Person and car.

The Owner can own one Car. The Car can be owned by one Owner.

So, the Owner hasOne Car, and the car belongsTo an Ownwe. So, the foreign key will go in "car". The car needs to know who it belongsTo.

In your case, the invoice needs to know who it belongs to, so, if a customer can have many invoices, customer hasMany(Invoice::class) and invoices belongsTo(Customer::class).

0
votes

If your 2 related tables/entities have a relationship as one-to-one they should be defined using hasOne.

If your 2 related tables/entities have a relationship as one-to-many like A has many B, then A should define B as hasMany and B should define A as belongsTo which will be called as One To Many (Inverse)

For your case both models could define each other as hasOne and inverse side of model should define owning model as belongsTo

  • An invoice hasOne customer , customer belongsTo invoice

  • A customer hasOne invoice, invoice belongsTo customer

In a one-to-one relationship the table/entity holding the foreign key of the related table/entity is always the owning side of the relation and other will be inverse side of relation.