何时/为何使用 hasMany 和 BelongsTo
在 Laravel 中,可以在模型中使用 hasMany()
和 belongsTo()
方法来指定表之间的关系。这适用于一对多关系。
为数据库指定了这种关系
$table->foreign('userId')->references('id')->on('users')
然而,在迁移文件中,这个关系也通过Why does it to bespecified double in Laravel? 。 为什么 Laravel 不从数据库中获取关系,我们是否必须双重指定它?
In Laravel it is possible to use the hasMany()
and belongsTo()
methods in the Model to specify the relation between tables. This for one-to-many relations.
However in the migration files, this relation is also specified for the database by the
$table->foreign('userId')->references('id')->on('users')
Why does it to be specified double in Laravel?
Why does Laravel doesn't fetch the relationship from the database, and do we have to specify it double?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Laravel 提供
hasMany()
和belongsTo()
等,以便更快地访问 model 级别的表之间的父/子记录。例如,您可以使用->{attr}
访问子记录,这使得子记录就像父记录的属性一样。它还具有其他好处,例如通过将关系参数提供到
->with()
函数来提前加载子记录。相比之下,迁移文件中关系的使用是在数据库级别上强制表之间的关系。
Laravel offers
hasMany()
andbelongsTo()
etc for quicker access to parent/child records between tables on the model level. For instance, you may access the child record with->{attr}
, which makes the child record as if an attribute of the parent record.It also comes with other benefits, such as eager loading of child record by providing the relationship parameter into
->with()
function.In comparison, the usage of relation in migration files are to enforce relationship between tables on database level.