Laravel 用戶之間關注

介紹

有關用戶之間的相互關注這樣的應用場景仍是很常見的 每一個平臺都會有這樣相似的需求 就好比Segmentfault知乎php

固然還有最熟悉的Github每一個人能夠有關注者和粉絲shell

創建模型表

這裏咱們去創建一箇中間表 能夠想象獲得的是這張表裏包含了兩個用戶的id 咱們能夠去建立一個Modeljson

$ 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

這樣的話咱們就能夠拿到對應的用戶數據信息了

其實整個實現起來就和咱們對一篇帖子進行點贊同樣 只不過對象變成了用戶與用戶之間

相關文章
相關標籤/搜索