如何在 Laravel 5 中为关系添加默认范围/条件?

Eve*_*ert 4 polymorphic-associations laravel eloquent laravel-5

所以我有一个名为的表files,其中包含一个文件列表,其中包含各自的名称、路径和文件类型。然后我还有一些其他表,可以附加文件。例如表user_profiles。最后,我有一个数据透视表,用于文件和其他表之间的多对多多态关系。数据透视表被称为fileables(想不出更好的名字)。现在,用户可能会在他们的个人资料中附加一些图片,可能还有一些视频,它们都来自文件。

通常,如果它只是图像,我会做这样的事情:

class UserProfile extends Model {

    public function images()
    {
        return $this->morphToMany('App\File', 'fileable');
    }

}
Run Code Online (Sandbox Code Playgroud)

但是,由于它是图像和视频,我想做这样的事情:

class UserProfile extends Model {

    public function images()
    {
        return $this->morphToMany('App\File', 'fileable')->where('type', 'LIKE', 'image%');
    }

    public function videos()
    {
        return $this->morphToMany('App\File', 'fileable')->where('type', 'LIKE', 'video%');
    }

}
Run Code Online (Sandbox Code Playgroud)

但这似乎不起作用。那么这样做的正确方法是什么?

Mar*_*ean 5

我会在你的File模型上创建范围:

public function scopeImages($query)
{
    return $query->where('type', 'LIKE', 'image/%');
}

public function scopeVideos($query)
{
    return $query->where('type', 'LIKE', 'video/%');
}
Run Code Online (Sandbox Code Playgroud)

然后在您的UserProfile模型中使用它们:

public function images()
{
    return $this->morphToMany('App\File', 'fileable')->images();
}

public function videos()
{
    return $this->morphToMany('App\File', 'fileable')->videos();
}
Run Code Online (Sandbox Code Playgroud)