简体   繁体   English

laravel eloquent 中的一对多关系

[英]One-To-Many Relationships in laravel eloquent

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.早上好,我在 Eloquent 中的模型关系方面遇到了一些麻烦,我需要将这些文章的文章和图像与中间表链接起来。 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?在中间表中,我想添加文章和图像的 ID,并且我想检索属于文章的所有图像,管理这种关系的最佳方法是什么? Thanks in advance提前致谢

You don't need to use pivot table since it'sone-to-many relationship.您不需要使用数据透视表,因为它是一对多的关系。

Just use hasMany() relation:只需使用hasMany()关系:

public function images()
{
    return $this->hasMany('App\Image');
}

And then use eager loading to load all images with article:然后使用预先加载来加载所有带有文章的图像:

$article = Article::with('images')->where('id', $articleId)->first();

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 relations allow 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!希望这有帮助!

In Image model class在图像模型类中

class Image extends Model
{

    public function article()
    {
        return $this->belongsTo(Article::class);
    }

}

Then you can access all the images that belong to Article as follows.然后您可以访问属于文章的所有图像,如下所示。

$image= Image::first();

Then for example when we want to get the name of the image that belongs to Article.然后例如当我们想要获取属于文章的图像的名称时。

$imageName = $image->article->name;

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

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