有關用戶之間的相互關注這樣的應用場景仍是很常見的 每一個平臺都會有這樣相似的需求 就好比Segmentfault和知乎php
固然還有最熟悉的Github
每一個人能夠有關注者和粉絲shell
這裏咱們去創建一箇中間表 能夠想象獲得的是這張表裏包含了兩個用戶的id
咱們能夠去建立一個Model
json
$ php artisan make:model Follow -m
建立完咱們的表以後 咱們去完善下表的字段信息數組
Schema::create('follows', function (Blueprint $table) { $table->increments('id'); $table->integer('follower_id')->unsigned()->index(); $table->integer('followed_id')->unsigned()->index(); $table->timestamps(); });
定義完畢以後去遷移下數據表post
$ php artisan migrate
寫完咱們的數據表 咱們是將關注的信息存放在follows
這個數據表的 由於這是用戶與用戶之間的關聯
並非以前的用戶與帖子或文章這樣的模型關聯 其實實現的道理是同樣的 this
咱們就能夠在User Model
裏去定義對應的關聯code
//用戶關注 public function following() { return $this->belongsToMany(self::class,'follows','follower_id','followed_id')->withTimestamps(); } //用戶的粉絲 public function followers() { return $this->belongsToMany(self::class,'follows','followed_id','follower_id')->withTimestamps(); } //關注用戶 public function followThisUser($user) { return $this->following()->toggle($user); }
由於用戶與用戶之間也是一種多對多的關係 因此我將關注用戶的方法寫成followThisUser
對象
接下來就能夠去定義相應的方法路由了 這裏爲了使用方便我定義了一個控制器路由
$ php artisan make:controller FollowController
首先咱們去定義一下咱們的路由rem
Route::post('/user/follow','FollowersController@follow');
若是用戶去關注另外一個用戶的話 只須要去執行follow
方法 而這個方法也是一個toggle
式的操做
固然咱們在執行
$follow = $user->followThisUser($userId)
這個方法是他會返回一個數組對象 若是是執行
attach
方法的話那麼
$follow['attached']
是$userId
的值若是這樣的話咱們就能夠知道
followThis
這個方法究竟是執行了attach
仍是detach
方法了
那麼接着咱們就能夠去增長一個用戶的粉絲數或者去通知用戶發送一個消息這樣的操做了
因此你能夠在執行完成以後的邏輯是這樣的
$follow = user()->followThisUser($userId); //若是用戶關注了另外一個用戶 if(count($followed['attached'])>0){ //能夠去通知用戶 修改用戶的關注人數等數據 return response()->json(['followed' => true]); }
固然若是咱們須要拿到一個用戶的關注的人和粉絲的話 能夠去執行
$user->following
以及
$user->followers
這樣的話咱們就能夠拿到對應的用戶數據信息了
其實整個實現起來就和咱們對一篇帖子進行點贊同樣 只不過對象變成了用戶與用戶之間