Reputation: 125
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
Upvotes: 3
Views: 11830
Reputation: 149
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;
Upvotes: 0
Reputation: 13693
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!
Upvotes: 0
Reputation: 163748
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();
Upvotes: 8