【问题标题】:How to create follower relationships using Eloquent and Laravel?如何使用 Eloquent 和 Laravel 创建追随者关系?
【发布时间】:2017-02-09 19:24:41
【问题描述】:

所以,我正在尝试建立一种用户可以关注其他用户或关注类别的关系。 我的直觉告诉我,到目前为止我所做的并不是正确的做事方式。我对如何创建 follower - followee 关系感到特别困惑。

表格:

用户

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

类别

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

关注

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();
        });
    }

型号:

用户

class User extends Model implements Authenticatable 
{

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

类别

class Category extends Model
{

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

关注

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

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    根据你的场景,建议你使用Polymorphic Many To Many关系。

    架构:

    users
        id - integer
        ...
    
    categories
        id - integer
        ...
    
    followables
        user_id - integer
        followable_id - integer
        followable_type - string
    

    型号:

    用户:

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

    类别:

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

    然后你可以创建这样的关系:

    关注用户时:

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

    关注类别时:

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

    希望对你有帮助。

    【讨论】:

    • 我确实尝试过,但它似乎试图将所有数据保存到 users 表而不是 followables 表。无论如何,我确实尝试使用您的建议来解决它,但我无法弄清楚。有这么多的新信息,所以我创建了一个新线程:stackoverflow.com/questions/42205928/…
    猜你喜欢
    • 2017-12-08
    • 2019-07-03
    • 2021-02-18
    • 2021-10-09
    • 1970-01-01
    • 2021-06-13
    • 1970-01-01
    • 2019-09-21
    • 1970-01-01
    相关资源
    最近更新 更多