【问题标题】:How can I add default scope / conditions on a relationship in Laravel 5?如何在 Laravel 5 中为关系添加默认范围/条件?
【发布时间】:2015-03-18 17:24:12
【问题描述】:

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

通常,如果只有图像,我会这样做:

class UserProfile extends Model {

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

}

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

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%');
    }

}

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

【问题讨论】:

  • “这似乎不起作用”不是很有帮助。

标签: laravel eloquent laravel-5 polymorphic-associations


【解决方案1】:

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

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

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

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

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

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

【讨论】:

  • 实际上,我发现我的代码确实有效。我只是有一个错字。但是你的代码更干净。 :-)
猜你喜欢
  • 1970-01-01
  • 2015-11-25
  • 1970-01-01
  • 2016-07-13
  • 2019-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多