laravel eloquent 中的一对多关系
One-To-Many Relationships in laravel eloquent
早上好,我在 Eloquent 中遇到了一些模型关系方面的问题,我需要 link 文章和具有中间 table 的文章的图像。在中间 table 我想添加文章和图像的 id,我想检索属于一篇文章的所有图像,管理关系的最佳方法是什么?提前致谢
您不需要使用枢轴 table,因为它是 one-to-many 关系。
只需使用hasMany()
关系:
public function images()
{
return $this->hasMany('App\Image');
}
然后使用eager loading加载文章的所有图像:
$article = Article::with('images')->where('id', $articleId)->first();
您可以使用 morphMany()
关系 (Polymorphic Relationship) 来解决您的问题:
更新:table结构如下:
- 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.
您的模型将如下所示:
class Article extends Model
{
public function images()
{
return $this->morphMany(Image::class, 'owner');
}
}
class Image extends Model
{
public function owner()
{
return $this->morphTo();
}
}
要将多张图片保存到一篇文章中,您可以这样做:
$article->images()->create([... inputs_arr ...]);
要获取它们,您可以这样做:
$articleImages = Article::find($id)->images;
希望对您有所帮助!
在图像模型中 class
class Image extends Model
{
public function article()
{
return $this->belongsTo(Article::class);
}
}
然后您可以访问属于文章的所有图片如下。
$image= Image::first();
然后比如我们想获取属于Article的图片的名称时
$imageName = $image->article->name;
早上好,我在 Eloquent 中遇到了一些模型关系方面的问题,我需要 link 文章和具有中间 table 的文章的图像。在中间 table 我想添加文章和图像的 id,我想检索属于一篇文章的所有图像,管理关系的最佳方法是什么?提前致谢
您不需要使用枢轴 table,因为它是 one-to-many 关系。
只需使用hasMany()
关系:
public function images()
{
return $this->hasMany('App\Image');
}
然后使用eager loading加载文章的所有图像:
$article = Article::with('images')->where('id', $articleId)->first();
您可以使用 morphMany()
关系 (Polymorphic Relationship) 来解决您的问题:
更新:table结构如下:
- 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.
您的模型将如下所示:
class Article extends Model
{
public function images()
{
return $this->morphMany(Image::class, 'owner');
}
}
class Image extends Model
{
public function owner()
{
return $this->morphTo();
}
}
要将多张图片保存到一篇文章中,您可以这样做:
$article->images()->create([... inputs_arr ...]);
要获取它们,您可以这样做:
$articleImages = Article::find($id)->images;
希望对您有所帮助!
在图像模型中 class
class Image extends Model
{
public function article()
{
return $this->belongsTo(Article::class);
}
}
然后您可以访问属于文章的所有图片如下。
$image= Image::first();
然后比如我们想获取属于Article的图片的名称时
$imageName = $image->article->name;