2016-03-13 107 views
1

我在問題中使用用戶/過帳示例。我有兩張用戶和帖子用post_views作爲表與多對多的關係鏈接在一起。此外,我創建了一個Event和Listener來處理帖子上的觀點。但是我只想添加一個新的視圖條目,如果一個給定的帖子的最後一個視圖在一個小時前被該用戶查看。Laravel在中間表上很多很多的過濾器雄辯

此刻我在UpdatePostViews聽衆handle()方法做:

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返回用戶/帖子組合的最後一行,因此我可以確定它在一小時前插入的時間戳,並添加新的輸入或跳過創建新條目。

回答

4

您可以使用BelongsToMany關係中的wherePivot方法在查詢的數據透視表上添加約束。

一旦你這樣做了,你可以使用邏輯的任意組合來確定是否在最近一小時有一個視圖。例如:

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

這也是一個很好的解決方案。接受你的答案,感到愚蠢的接受我自己的問題的答案;)在我的情況下,用戶已經存在於$事件對象。謝謝! +1 – Ben

+0

你對我的回答的評論是正確的。我刪除了自己的答案,因爲這是錯誤的答案。感謝您的進一步解釋! – Ben