Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use belongsTo() and when hasOne() in laravel?

Tags:

php

laravel

When defining a one-to-one relationship between models in laravel, we will say :

class Model1 extends Model
{
     public function model2()
     { 
         return $this->hasOne('App\Model2');
     }
}

and for Model2 we will use belongsTo('App\Model1') .

Is there a logic on how to decide on which end we will use each function?

like image 323
orestiss Avatar asked Nov 10 '15 15:11

orestiss


People also ask

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 belongsTo in laravel?

BelongsTo relationship in laravel is used to create the relation between two tables. belongsTo means create the relation one to one in inverse direction or its opposite of hasOne. For example if a user has a profile and we wanted to get profile with the user details then we can use belongsTo relationship.

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 belongsTo?

BelongsTo is a inverse of HasOne. We can define the inverse of a hasOne relationship using the belongsTo method. Take simple example with User and Phone models. I'm giving hasOne relation from User to Phone. class User extends Model { /** * Get the phone record associated with the user.


Video Answer


1 Answers

The difference between the two is where the foreign key will reside in the database. The belongsTo function should belong to the model whose table contains the foreign key, while the hasOne should belong to a model that is referenced by a foreign key from another table.

Both will work, but you should maintain solid coding practices for other developers that may use your system in the future. Also, this becomes crucial if your foreign key cascades the delete. If you delete model1, should model2 that belongsTo model1 be deleted also?

like image 154
Mikel Bitson Avatar answered Oct 06 '22 15:10

Mikel Bitson