首页 > 解决方案 > 如何使用 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 (模型)上编写函数以根据文件类型过滤掉产品的最佳方法是什么?

标签: phplaraveleloquent

解决方案


因为它是 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;

推荐阅读