One-To-Many Relationships in laravel eloquent

旧城冷巷雨未停 提交于 2019-12-11 05:16:23

问题


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


回答1:


You can use morphMany() relationship (Polymorphic Relationship) to solve your problem like this:

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!




回答2:


You don't need to use pivot table since it's one-to-many relationship.

Just use hasMany() relation:

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();


来源:https://stackoverflow.com/questions/40976917/one-to-many-relationships-in-laravel-eloquent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!