如何在多态关系中排除急切加载的查询?

时间:2018-06-09 14:29:25

标签: laravel eloquent eager-loading

让我们说这是我的桌面结构:

posts
    id - integer
    title - string
    body - text
    reviewed - boolean

videos
    id - integer
    title - string
    url - string

profileContent
    id - integer
    user_id - integer
    content_id - integer
    content_type - string

现在我想收到用户个人资料的内容:

$user->profileContents()
     ->latest()
     ->with(['content' => function ($query){
        //I'm not sure how to do it
     }])
     ->paginate(5);

我怎么说如果列#34;已审核"存在应该是真的吗?但视频是否经过审核并不重要。

其他信息:

profileContents()为我提供了用户个人资料的所有内容

public function profileContents()
{
    return $this->hasManyThrough(ProfileContent::class, Profile::class);
}

和('内容')用于转换为特定模型:

public function content()
{
    return $this->morphTo();
}

修改1:

我离我的目标更近了。我使用GlobalScope只显示经过审核的内容。

在帖子中:

protected static function boot()
{
    parent::boot();

    static::addGlobalScope('reviewed', function (Builder $builder) {
        $builder->where('reviewed', true);
    });
}

但是现在我遇到的问题是我仍然无法排除空查询。我告诉你输出:

//ProfileContent
array:2 [
  0 => array:8 [
    "id" => 1
    "profile_id" => "1"
    "content_id" => "1"
    "content_type" => "App\Video"
    "content" => "[some array values]"
  ]
  1 => array:8 [
    "id" => 2
    "profile_id" => "1"
    "content_id" => "1"
    "content_type" => "App\Post"
    "content" => null
  ]
]

如何在不丢失分页数据的情况下排除空数组(输出应为5)

1 个答案:

答案 0 :(得分:0)

再次检查您的问题,您正在访问关系,然后尝试再次加载关系。我很确定这就是你想要的:

$user->contents()
     ->latest()
     ->with(['posts' => function ($query){
      //here you add a query constrain on eagerload like:

        $query->where('reviewed', true);  
     }])
     ->paginate(5);
相关问题