简体   繁体   中英

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

You don't need to use pivot table since it'sone-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();

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!

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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