php - 如何使用 Eloquent 从文件表中检索某些文件类型?
问题描述
考虑到产品在电子商务网站上有图像、视频和 PDF 文件……。
我希望能够根据文件类型调用一个雄辩的调用,例如:
图像:
$product->file->images()
将为产品提供一个雄辩的图像集合......
视频:
$product->file->videos()
将为产品提供一个雄辩的视频集合...
PDF:
$product->file->pdf()
将为产品提供一个雄辩的 pdf 集合...
到目前为止,我只有一个Product.php(模型):
/**
* The relationships that should always be loaded.
*
* @var array
*/
protected $with = ['file'];
public function file()
{
return $this->hasMany(File::class, 'file_refer_id', 'id');
}
还有一个File.php(模型):
public function product()
{
return $this->belongsTo(Product::class, 'file_refer_id', 'id');
}
其中包含产品和文件之间的适当关系。
在 File.php (模型)上编写函数以根据文件类型过滤掉产品的最佳方法是什么?
解决方案
因为它是 Product 和 File 之间的一对多关系,所以让我们将关系重命名为 files()。
这可以实现您的结果:
class Product extends Model
{
public function files()
{
return $this->hasMany(File::class, 'file_refer_id', 'id');
}
public function images()
{
return $this->files()->where('type', 1);
}
public function videos()
{
return $this->files()->where('type', 2);
}
public function pdfs()
{
return $this->files()->where('type', 3);
}
}
因此,您可以通过以下方式获取 $videos、pdf 和图像:
$product->videos;
$product->pdfs;
$product->images;
推荐阅读
- python - python程序中列表中的排序函数?
- symfony - 无法安装 Symfony
- android - 如何在 NavigationView 中更改 SUBTITLE textAppearance?
- lisp - 试图计算总工资
- php - PHP If Else 控制结构的替代语法
- javascript - 跨度上的 javascript getElementById
- javascript - 其他所有请求的状态 500“错误:无法处理请求”
- php - 创建从数据库中删除数据的函数的困难
- laravel - Laravel 8 axios 获取 - 未经授权
- python - 替换列值取决于熊猫中的其他列和条件