简体   繁体   English

何时使用belongsTo()和laOvel中的hasOne()?

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

When defining a one-to-one relationship between models in laravel, we will say : 在laravel中定义模型之间的一对一关系时,我们会说:

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

and for Model2 we will use belongsTo('App\\Model1') . 对于Model2,我们将使用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. belongsTo函数应属于其表包含外键的模型,而hasOne应属于由另一个表中的外键引用的模型。

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? 如果删除model1,还应该删除belongsTo model1的model2吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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