From 2386dd55b94e57e4f4391b8fe5fc87890861e50c Mon Sep 17 00:00:00 2001 From: overtrue Date: Thu, 8 Jul 2021 18:06:49 +0800 Subject: [PATCH] Fixed #161. --- src/Followable.php | 7 +++++-- tests/FeatureTest.php | 4 ++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/Followable.php b/src/Followable.php index de2dae1..b7495da 100644 --- a/src/Followable.php +++ b/src/Followable.php @@ -190,14 +190,17 @@ public function attachFollowStatus($followables, callable $resolver = null) \abort_if(!($followables instanceof Collection), 422, 'Invalid $followables type.'); - $followed = $this->followings()->wherePivot('accepted_at', '!=', null)->pluck('following_id'); + $followed = UserFollower::where('follower_id', $this->getKey())->get(); $followables->map(function ($followable) use ($followed, $resolver) { $resolver = $resolver ?? fn ($m) => $m; $followable = $resolver($followable); if ($followable && \in_array(Followable::class, \class_uses($followable))) { - $followable->setAttribute('has_followed', $followed->contains($followable->getKey())); + $item = $followed->where('following_id', $followable->getKey())->first(); + $followable->setAttribute('has_followed', !!$item); + $followable->setAttribute('followed_at', $item ? $item->created_at : null); + $followable->setAttribute('follow_accepted_at', $item ? $item->accepted_at : null); } }); diff --git a/tests/FeatureTest.php b/tests/FeatureTest.php index f31396f..e6370fe 100644 --- a/tests/FeatureTest.php +++ b/tests/FeatureTest.php @@ -2,6 +2,7 @@ namespace Tests; +use Illuminate\Support\Carbon; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Event; use Overtrue\LaravelFollow\Events\Followed; @@ -207,9 +208,12 @@ function () use ($user1, $users) { $this->assertFalse($users[0]->has_followed); $this->assertTrue($users[1]->has_followed); + $this->assertInstanceOf(Carbon::class, $users[1]->followed_at); + $this->assertTrue($users[2]->has_followed); $this->assertTrue($users[3]->has_followed); + // with custom resolver $posts = \collect(['author' => $user2], ['author' => $user3], ['author' => $user4]); $user1->attachFollowStatus($posts, fn ($post) => $post['author']);