diff --git a/src/Cmgmyr/Messenger/Models/Thread.php b/src/Cmgmyr/Messenger/Models/Thread.php index 74018db..285b5c8 100644 --- a/src/Cmgmyr/Messenger/Models/Thread.php +++ b/src/Cmgmyr/Messenger/Models/Thread.php @@ -131,6 +131,22 @@ public function scopeForUserWithNewMessages($query, $userId) ->select('threads.*'); } + /** + * Returns threads between given user ids + * + * @param $query + * @param $participants + * @return mixed + */ + public function scopeBetween($query, array $participants) + { + $query->whereHas('participants', function ($query) use ($participants) { + $query->whereIn('user_id', $participants) + ->groupBy('thread_id') + ->havingRaw('COUNT(thread_id)='.count($participants)); + }); + } + /** * Adds users to this thread * diff --git a/tests/EloquentThreadTest.php b/tests/EloquentThreadTest.php index a5066a7..236a56e 100644 --- a/tests/EloquentThreadTest.php +++ b/tests/EloquentThreadTest.php @@ -121,6 +121,23 @@ public function it_should_get_all_threads_for_a_user_with_new_messages() $this->assertCount(1, $threads); } + /** @test */ + public function it_should_get_all_threads_shared_by_specified_users() + { + $userId = 1; + $userId2 = 2; + + $thread = $this->faktory->create('thread'); + $thread2 = $this->faktory->create('thread'); + + $this->faktory->create('participant', ['user_id' => $userId, 'thread_id' => $thread->id]); + $this->faktory->create('participant', ['user_id' => $userId2, 'thread_id' => $thread->id]); + $this->faktory->create('participant', ['user_id' => $userId, 'thread_id' => $thread2->id]); + + $threads = Thread::between([$userId, $userId2])->get(); + $this->assertCount(1, $threads); + } + /** @test */ public function it_should_add_participants_to_a_thread() {