@@ -59,21 +59,25 @@ public function follow(Request $request, FeedTopicModel $model, int $topicID): R
59
59
// If the topic Non-existent, throw a not found exception.
60
60
if (! $ topic ) {
61
61
throw new NotFoundHttpException ('关注的话题不存在 ' );
62
- } elseif ($ topic ->users ()->newPivotStatementForId ($ user ->id )->exists () ) {
62
+ } elseif (( $ link = $ topic ->users ()->newPivotStatementForId ($ user ->id )->first ())-> following_at ?? false ) {
63
63
return (new Response ())->setStatusCode (Response::HTTP_NO_CONTENT /* 204 */ );
64
64
}
65
65
66
66
$ feedsCount = $ topic ->feeds ()->where ('user_id ' , $ user ->id )->count ();
67
67
68
- return $ user ->getConnection ()->transaction (function () use ($ topic , $ user , $ feedsCount ): Response {
69
- $ topic ->users ()->attach ($ user , [
70
- 'following_at ' => new Carbon (),
71
- 'feeds_count ' => $ feedsCount ,
72
- ]);
73
- $ topic ->followers_count += 1 ;
74
- $ topic ->save ();
68
+ return $ user ->getConnection ()->transaction (function () use ($ topic , $ user , $ feedsCount , $ link ): Response {
69
+ if ($ link ) {
70
+ $ link ->following_at = new Carbon ;
71
+ $ link ->save ();
72
+ } else {
73
+ $ topic ->users ()->attach ($ user , [
74
+ 'following_at ' => new Carbon (),
75
+ 'feeds_count ' => $ feedsCount ,
76
+ ]);
77
+ }
78
+ $ topic ->increment ('followers_count ' , 1 );
75
79
76
- return (new Response () )->setStatusCode (Response::HTTP_NO_CONTENT /* 204 */ );
80
+ return (new Response )->setStatusCode (Response::HTTP_NO_CONTENT /* 204 */ );
77
81
});
78
82
}
79
83
@@ -102,19 +106,21 @@ public function unfollow(Request $request, FeedTopicModel $model, int $topicID):
102
106
}
103
107
104
108
// Create success 204 response
105
- $ response = (new Response () )->setStatusCode (Response::HTTP_NO_CONTENT /* 204 */ );
109
+ $ response = (new Response )->setStatusCode (Response::HTTP_NO_CONTENT /* 204 */ );
106
110
107
111
// If not followed, return 204 response.
108
- if (! $ topic ->users ()->newPivotStatementForId ($ user ->id )->first ()) {
112
+ if (! (( $ link = $ topic ->users ()->newPivotStatementForId ($ user ->id )->first ())-> following_at ?? false )) {
109
113
return $ response ;
110
114
}
111
115
112
- return $ user ->getConnection ()->transaction (function () use ($ topic , $ response , $ user ): Response {
113
- $ topic ->users ()->detach ($ user );
116
+ return $ user ->getConnection ()->transaction (function () use ($ topic , $ response , $ user , $ link ): Response {
114
117
if ($ topic ->followers_count > 0 ) {
115
118
$ topic ->decrement ('followers_count ' , 1 );
116
119
}
117
120
121
+ $ link ->following_at = null ;
122
+ $ link ->save ();
123
+
118
124
return $ response ;
119
125
});
120
126
}
0 commit comments