简体   繁体   English

如何使用Eloquent和Laravel创建关注者关系?

[英]How to create follower relationships using Eloquent and Laravel?

So, I'm trying to create a relationship where users can follow other users or follow categories. 因此,我正在尝试创建一种关系,使用户可以关注其他用户或关注类别。 My intuition says that what I've done so far is not the right way of doing things. 我的直觉说,到目前为止我做的不是正确的做事方式。 I'm especially confounded by how to create the follower - followee relationship. 我对如何建立追随者 - 追随者关系感到困惑。

TABLES: 表:

Users 用户

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('email');
            $table->string('password');
            $table->string('first_name');
        });
    }

Categories 分类

public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('category');
        });
    }

Follows 如下

public function up()
    {
        Schema::create('follows', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('follower_id');
            $table->integer('followee_id')->nullable();
            $table->integer('category_id')->nullable();
        });
    }

MODELS: 楷模:

User 用户

class User extends Model implements Authenticatable 
{

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

Category 类别

class Category extends Model
{

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

Follow 跟随

class Follow extends Model
{
    public function post()
    {
        return $this->belongsTo('App\User');
    }
    public function source()
    {
        return $this->belongsTo('App\Category');
    }
}

According to your scenario, it is recommended that you use Polymorphic Many To Many relationship. 根据您的方案,建议您使用Polymorphic Many To Many关系。

Schema: 架构:

users
    id - integer
    ...

categories
    id - integer
    ...

followables
    user_id - integer
    followable_id - integer
    followable_type - string

Models: 楷模:

User: 用户:

public function followers()
{
    return $this->morphToMany(User::class, 'followables');
}
public function following()
{
    return $this->morphedByMany(User::class, 'followables');
}

Category: 类别:

public function followers()
{
    return $this->morphToMany(User::class, 'followables');
}

Then you can create the relationship like: 然后,您可以创建如下关系:

When following an User: 当关注用户时:

$user->followers()->create(['user_id' => 12])

When following a Category: 遵循类别时:

$category->followers()->create(['user_id' => 25])

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM