阐明如何在Laravel的雄辩的ORM中建立一对多关系 [英] Clarify how to setup a one-to-many relationship in Laravel's Eloquent ORM

查看:82
本文介绍了阐明如何在Laravel的雄辩的ORM中建立一对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我正在研究Laravel 4文档,以在两个模型之间建立一对多关系.显然,一侧应使用hasMany().但另一方面,我应该使用hasOne还是belongsTo?有关系吗?有什么区别?为什么两者都存在?

Okay, I'm working through the Laravel 4 docs to setup a one-to-many relationship between two models. Obviously, one side should use hasMany(). But for the other side, should I use hasOne or belongsTo? Does it matter? What's difference? Why do both exist?

我曾经以为hasOne将用于一对一的关系,belongsTo将用于一对多的一侧.但是在文档中,用于在此处插入相关模型:

I had thought hasOne would be for one-to-one relationships, and belongsTo would be for the one side of one-to-many. But in the docs, for inserting a related model here:

http://laravel.com/docs/eloquent#inserting-related-models

他们使用的save()似乎只存在于hasOnehasMany关系中,而不存在于belongsTo中.看来belongsToassociate()用于相同的目的:

they are using save() which seems to only be present in hasOne and hasMany relationships, not in belongsTo. It looks like belongsTo uses associate() for the same purpose:

https://github.com/laravel/framework/blob/master/src/Illuminate/Database/Eloquent/Relations/BelongsTo.php#L188

也许我只需要了解何时使用belongsTohasOne的一般背景,以及为什么belongsTo使用associate()hasOne使用save()的原因.

Maybe I just need some general background on when to use belongsTo vs. hasOne, and why belongsTo uses associate() while hasOne uses save().

我想我的困惑点是在文档中( http://laravel.com/docs/eloquent#inserting-related-models ),它们使用了:

I guess my point of confusion was that in the docs (http://laravel.com/docs/eloquent#inserting-related-models), they used:

$post->comments()->save($comment);

我本该使用的地方:

$comment->post()->associate($post);

一种方式或另一种方式有优势吗?还是仅仅是在上下文中什么才有意义的问题?

Is there an advantage to one way or the other? Or is it just a question of what makes sense in the context?

推荐答案

请参阅laravel文档,以了解帖子和评论之间的一对多关系

Please refer to the laravel docs on the one to many relationship between posts and comments http://laravel.com/docs/eloquent#relationships. (Where one post has many comments and a comment belongs to a post).

帖子和评论表如下

帖子表 id |标题|身体

Posts Table id | title | body

评论表 id |评论| post_id

Comments Table id | comment | post_id

包含外键的数据库表属于另一个表中的记录,因此,在注释模型中,必须指定注释属于帖子.

The database table that contains a foreign key belongs to a record in the other table, therefore, in the comments model you must specify that comments belongs to posts.

您正确的说,hasOne关系仅适用于一对一关系.

You are correct that the hasOne relationship only applies to one to one relationships.

这是一篇带有laravel 3代码的博客文章,其中解释了雄辩的关系方法的工作原理.

Here is a blog post with laravel 3 code which gives an explanation into how eloquent relationship methods work.

> http://laravel.io/topic/14/how-eloquent-relationship-methods -工作

这篇关于阐明如何在Laravel的雄辩的ORM中建立一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆