简体   繁体   中英

When to use belongsTo() and when hasOne() in 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?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM