laravel eloquent 中的一对多关系
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40976917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
One-To-Many Relationships in laravel eloquent
提问by Santiago Capdevila
Good morning, I am having a little trouble with model relationships in Eloquent, I need to link articles and images for those articles with an intermediate table. In the intermediate table I'd like to add the id's of both article and image, and I would like to retrieve all the images belonging to an article, what would be the best way to manage the relationship? Thanks in advance
早上好,我在 Eloquent 中的模型关系方面遇到了一些麻烦,我需要将这些文章的文章和图像与中间表链接起来。在中间表中,我想添加文章和图像的 id,并且我想检索属于文章的所有图像,管理关系的最佳方法是什么?提前致谢
采纳答案by Saumya Rastogi
You can use morphMany()
relationship (Polymorphic Relationship) to solve your problem like this:
您可以使用morphMany()
关系(多态关系)来解决您的问题,如下所示:
UPDATE: The table structure goes like this:
更新:表结构如下:
- articles
- id
- title
- content
- ...
- images
- id
- owner_id
- owner_type (Here there can be - Article, Auction, User, etc)
- name
- mime_type
- ...
Polymorphic relationsallow a model to belong to more than one other model on a single association. For example, imagine users of your application can "comment" both posts and videos. Using polymorphic relationships, you can use a single comments table for both of these scenarios.
多态关系允许一个模型在单个关联上属于多个其他模型。例如,假设您的应用程序的用户可以“评论”帖子和视频。使用多态关系,您可以对这两种情况使用单个注释表。
You models will look like this:
您的模型将如下所示:
class Article extends Model
{
public function images()
{
return $this->morphMany(Image::class, 'owner');
}
}
class Image extends Model
{
public function owner()
{
return $this->morphTo();
}
}
To save multiple images to an article, you can do like:
要将多个图像保存到文章中,您可以执行以下操作:
$article->images()->create([... inputs_arr ...]);
and to fetch them, you can do this like:
并获取它们,您可以这样做:
$articleImages = Article::find($id)->images;
Hope this helps!
希望这可以帮助!
回答by Alexey Mezenin
You don't need to use pivot table since it's one-to-manyrelationship.
您不需要使用数据透视表,因为它是一对多的关系。
Just use hasMany()
relation:
只需使用hasMany()
关系:
public function images()
{
return $this->hasMany('App\Image');
}
And then use eager loadingto load all images with article:
然后使用预先加载来加载所有带有文章的图像:
$article = Article::with('images')->where('id', $articleId)->first();