Laravel Eloquent在中间表上进行了多对多的过滤

时间:2016-03-13 08:33:10

标签: php laravel eloquent many-to-many

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

目前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();

将从post_views返回用户/帖子组合的最后一行,以便我可以确定它在一小时前插入的时间戳,并添加新条目或跳过创建新条目。 / p>

1 个答案:

答案 0 :(得分:4)

您可以使用wherePivot关系上的BelongsToMany方法为查询的数据透视表添加约束。

一旦这样做,您可以使用任何逻辑组合来确定过去一小时是否有视图。类似的东西:

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