【问题标题】:Laravel follower/following relationshipsLaravel 追随者/追随者关系
【发布时间】:2017-12-08 08:46:34
【问题描述】:

我正在尝试在laravel中做一个简单的关注者/关注系统,没什么特别的,只需点击一个按钮即可关注或取消关注,并显示关注者或关注你的人。

我的麻烦是我不知道如何建立模型之间的关系。

这些是迁移:

-用户迁移:

Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
        $table->string('email');
        $table->string('first_name');
        $table->string('last_name');
        $table->string('password');
        $table->string('gender');
        $table->date('dob');
        $table->rememberToken();
    });

-追随者迁移:

Schema::create('followers', function (Blueprint $table) {

        $table->increments('id');
        $table->integer('follower_id')->unsigned();
        $table->integer('following_id')->unsigned();
        $table->timestamps();        
    });
}

以下是模型:

-用户模型:

   class User extends Model implements Authenticatable
{
    use \Illuminate\Auth\Authenticatable;
    public function posts()
    {
        return $this->hasMany('App\Post');
    }

    public function followers()
    {
        return $this->hasMany('App\Followers');
    }

}

-追随者模型基本上是空的,这就是我卡住的地方

我尝试过这样的事情:

class Followers extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

但是没有用。

另外,我想问一下您能否告诉我如何编写“关注”和“显示关注者/关注”功能。我已经阅读了我能找到的所有教程,但没有用。我似乎无法理解。

【问题讨论】:

    标签: php laravel relationships


    【解决方案1】:

    您需要意识到“追随者”也是App\User。所以这两种方法只需要一个模型App\User

    // users that are followed by this user
    public function following() {
        return $this->belongsToMany(User::class, 'followers', 'follower_id', 'following_id');
    }
    
    // users that follow this user
    public function followers() {
        return $this->belongsToMany(User::class, 'followers', 'following_id', 'follower_id');
    }
    

    用户$a想关注用户$b

    $a->following()->attach($b);
    

    用户$a想停止关注用户$b

    $a->following()->detach($b);
    

    获取用户$a的所有关注者:

    $a_followers = $a->followers()->get();
    

    【讨论】:

    • 天哪!谢谢一百万!
    • 如果你想显示关注者的数量,你可以使用 $a->followers()->get()->count() 吗?还是我会将查询写入 count 方法?
    猜你喜欢
    • 2019-07-03
    • 2021-10-09
    • 1970-01-01
    • 2021-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    相关资源
    最近更新 更多