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

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

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

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

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

+7
php laravel
source share
1 answer

The difference between the two is where the foreign key will be in the database. The belongsTo function must belong to the model whose table contains the foreign key, and hasOne must belong to the model referred to by the foreign key from another table.

Both will work, but you must support robust coding techniques for other developers who may use your system in the future. In addition, it becomes crucial if your foreign key cascades deletion. If you delete model1, should model2, which belongs to model1, also be deleted?

+9
source share

All Articles