问题
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