laravel雄辩的一对多关系 [英] One-To-Many Relationships in laravel eloquent

查看:78
本文介绍了laravel雄辩的一对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早上好,我在Eloquent的模型关系上遇到了一些麻烦,我需要将这些文章和文章的图像与中间表链接起来.在中间表中,我想同时添加文章和图像的ID,并且我想检索属于文章的所有图像,那么管理这种关系的最佳方法是什么?预先感谢

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

推荐答案

您可以使用morphMany()关系(多态关系)来解决您的问题,

You can use morphMany() relationship (Polymorphic Relationship) to solve your problem 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.

您的模型将如下所示:

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;

希望这会有所帮助!

这篇关于laravel雄辩的一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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