【发布时间】:2013-05-27 23:32:58
【问题描述】:
好的,我正在研究 Laravel 4 文档以在两个模型之间建立一对多的关系。显然,一侧应该使用 hasMany()。但另一方面,我应该使用 hasOne 还是 belongsTo?有关系吗?有什么区别?为什么两者都存在?
我原以为 hasOne 用于一对一关系,belongsTo 用于一对多的一方。但在文档中,用于在此处插入相关模型:
http://laravel.com/docs/eloquent#inserting-related-models
他们正在使用save(),它似乎只存在于hasOne 和hasMany 关系中,而不存在于belongsTo 中。看起来belongsTo 使用associate() 用于相同目的:
也许我只需要一些关于何时使用belongsTo 和hasOne 的一般背景知识,以及为什么belongsTo 使用associate() 而hasOne 使用save()。
编辑:我想我的困惑是在文档 (http://laravel.com/docs/eloquent#inserting-related-models) 中,他们使用了:
$post->comments()->save($comment);
我会使用的地方:
$comment->post()->associate($post);
一种方式或另一种方式有优势吗?还是只是一个在上下文中有意义的问题?
【问题讨论】:
标签: php orm laravel laravel-4 eloquent