Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 348
Santiago Capdevila Avatar asked Dec 11 '25 05:12

Santiago Capdevila


1 Answers

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();
like image 185
Alexey Mezenin Avatar answered Dec 13 '25 17:12

Alexey Mezenin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!