Skip to content
Advertisement

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. 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

Advertisement

Answer

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!

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement