Php 如何使用与Laravel的多态多对多关系创建跟随者关系?

Php 如何使用与Laravel的多态多对多关系创建跟随者关系?,php,laravel,eloquent,many-to-many,polymorphic-associations,Php,Laravel,Eloquent,Many To Many,Polymorphic Associations,好的,所以我试图建立一种关系,用户可以跟随其他用户或类别。我得到了使用关系的建议。现在我正试图建立一种跟随者-跟随者的关系,但我无法理解如何设置模型和控制器 表格 使用者 类别 Schema::create('categories', function (Blueprint $table) { $table->increments('id'); $table->string('category'); })

好的,所以我试图建立一种关系,用户可以跟随其他用户或类别。我得到了使用关系的建议。现在我正试图建立一种跟随者-跟随者的关系,但我无法理解如何设置模型和控制器

表格

使用者

类别

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

        Schema::create('followables', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
            $table->integer('user_id');
            $table->integer('followable_id');
            $table->string('followable_type');
        });
型号

使用者

可遵循

class Followable extends Model
{

    protected $fillable = ['user_id'];

    public function followable()
    {
        return $this->morphTo();
    }

}
-------------------------------------------------
|Id | user_id | followable_id | followable_type |
-------------------------------------------------
|22  | 4       | NULL          | NULL            |
-------------------------------------------------
|23  | 0       | 22            | App\User        |
-------------------------------------------------
类别模型跟随者关系还不存在,所以我暂时不考虑这个问题

控制器

跟随控制器

class FollowableController extends Controller
{

    public function followUser($followable_id){

        $user_id = Auth::user()->getId();
        $followee = User::find($followable_id);
        $followee->followers()->create(['user_id' => $user_id]);


        return redirect()->route('get.user', ['user_id' => $followable_id]);
    }

}
老实说,我对我创建的代码有点困惑。这是一些复制和粘贴,而不是100%理解我所做的。无论如何,这将在数据库中创建两条记录,如下所示:

可遵循

class Followable extends Model
{

    protected $fillable = ['user_id'];

    public function followable()
    {
        return $this->morphTo();
    }

}
-------------------------------------------------
|Id | user_id | followable_id | followable_type |
-------------------------------------------------
|22  | 4       | NULL          | NULL            |
-------------------------------------------------
|23  | 0       | 22            | App\User        |
-------------------------------------------------
可跟随_id错误,似乎使用了在可跟随表中创建的id,而不是用户表中的用户_id


那么,如何解决这样的问题,使只有一条记录被保存到具有可右跟随id的数据库中?

我猜您使用了错误的方法。我按照Laravel的doc示例做了类似的操作,
morphMany()
就足够了,因为您的
User
可以有很多追随者,他们本身就是
User
,因此您可以:

用户
型号:

public function followers()
{
    return $this->morphMany('App\Followable', 'followable');
}
然后您可以从控制器设置用户id(但不要忘记将其添加到fillable)


希望有帮助:)

当我尝试这一个时,没有任何东西保存到数据库中。还有什么我需要更改的吗?@AdamDedanga,你确定你有正确的字段作为这些表的外键吗。你能找到解决方案吗?你解决了吗?我想这次你必须将它显式地添加到用户模型中的
follower()
关系函数中,即
return$this->morphMany('App\Followable','Followable',null,'Followable_id')