Laravel Eloquent 中间的多对多过滤器 table

Laravel Eloquent many to many filter on intermediate table

我在问题中使用了 User/Post 示例。我有两个 tables 用户和帖子链接在一起,与 post_views 作为 table 的多对多关系。我还创建了一个事件和监听器来处理 post 上的视图。但我只想添加一个新的视图条目,如果给定 post 的最后一个视图是该用户一个多小时前。

目前我的 handle() 方法在 UpdatePostViews 侦听器中执行:

public function handle(PostWasViewed $event)
{
    $event->post->views()->attach($event->user->id);
}

关系是用 withTimestamps 定义的,但是我如何在 handle() 方法中进行过滤以执行类似

的操作
    $lastView = User::where('user_id', $userId)
->where('post_id', $postId)
->in('post_views')
->orderBy('id', 'DESC')
->first();

return 来自 post_views 的 user/post 组合的最后一行,这样我就可以确定一个多小时前插入的时间戳并添加一个新条目或跳过创建新条目。

您可以在 BelongsToMany 关系上使用 wherePivot 方法为查询添加对枢轴 table 的约束。

执行此操作后,您可以使用任意逻辑组合来确定过去一小时内是否有浏览。类似于:

public function handle(PostWasViewed $event)
{
    $inLastHour = $event->user->posts()->where('id', $event->post->id)->wherePivot('updated_at', '>=', new \Illuminate\Database\Query\Expression('NOW() - INTERVAL 1 HOUR'))->exists();

    // or, either way, shouldn't matter

    $inLastHour = $event->post->views()->where('id', $event->user->id)->wherePivot('updated_at', '>=', new \Illuminate\Database\Query\Expression('NOW() - INTERVAL 1 HOUR'))->exists();

    if (!$inLastHour) {
        $event->post->views()->attach($event->user->id);
    }
}