Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should i use belongsTo or hasOne in Laravel?

Tags:

laravel

Consider two models A and B

A -> relatedTo B is a one to one relationship

What is the difference in using (A ->hasOne-- B) and (A ->belongsTo-- B)?

Can I use them interchangeably?

like image 384
wolfgang Avatar asked May 05 '15 16:05

wolfgang


People also ask

What is the difference between hasOne and belongsTo laravel?

The only difference between hasOne and belongsTo is where the foreign key column is located. Let's say you have two entities: User and an Account. In short hasOne and belongsTo are inverses of one another - if one record belongTo the other, the other hasOne of the first.

What is the difference between hasMany and belongsTo?

belongsTo(B) association means that a One-To-One relationship exists between A and B , with the foreign key being defined in the source model ( A ). The A. hasMany(B) association means that a One-To-Many relationship exists between A and B , with the foreign key being defined in the target model ( B ).

What is hasOne laravel?

hasOne relationship in laravel is used to create the relation between two tables. hasOne means create the relation one to one. For example if a article has comments and we wanted to get one comment with the article details then we can use hasOne relationship or a user can have a profile table.

What is eager load in laravel?

Laravel eager loading. What is eager loading? Eager loading is a concept in which when retrieving items, you get all the needed items together with all (or most) related items at the same time. This is in contrast to lazy loading where you only get one item at one go and then retrieve related items only when needed.


2 Answers

No, the difference depends on where your foreign key is.

In your example, if A has a b_id column, then A belongsTo B.

If B has an a_id column, then A hasOne or hasMany B depending on how many B should have.

like image 120
user1669496 Avatar answered Oct 05 '22 23:10

user1669496


Main difference is as below:

belongsTo and belongsToMany - you're telling Laravel that this table holds the foreign key that connects it to the other table.

hasOne and hasMany - you're telling Laravel that this table does not have the foreign key.

like image 35
Abid Ali Avatar answered Oct 06 '22 01:10

Abid Ali