Laravel 追随者/追随者关系 -Profile 到 Profile 命名约定

我正在尝试在 Laravel 中创建多对多的以下关系。到目前为止,我发现所有的解决方案,例如这个Laravel 关注者/关注关系,都是用户可以关注个人资料的地方。在我的情况下,一个用户可以有很多个人资料,所以我想这样做,以便个人资料可以跟随个人资料。


我是 Laravel 的新手,被告知有一个命名约定。我创建了迁移


php artisan make:migration creates_profile_profile_pivot_table --create profile_profile


这是我的架构


    public function up()

    {

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

            $table->bigIncrements('id');

            $table->unsignedBigInteger('profile_id');

            $table->unsignedBigInteger('profile_id');

            $table->timestamps();

        });

    }


我得到错误


   Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1 duplicate column name: profile_id (SQL: create table "profile_profile" ("id" integer not null primary key autoincrement, "profile_id" integer not null, "profile_id" integer not null, "created_at" datetime null, "updated_at" datetime null))


如果我将两个 profile_id 替换为 following_id 和 follower_id 会与命名约定冲突吗?


慕沐林林
浏览 137回答 1
1回答

幕布斯6054654

对于这种情况,您无法遵循命名约定:您必须按照您的建议为第二个外键指定不同的名称。这不会导致任何问题,但是当您在Profile模型中创建关系时,您必须手动指定外键,如果您遵循约定,Laravel 会自动执行此操作。假设另一个外键被称为follower_id,模型关系将如下所示:public function followers(){    return $this->belongsToMany('App\Profile', 'profile_profile', 'profile_id', 'follower_id')->withTimestamps();}public function followed(){    return $this->belongsToMany('App\Profile', 'profile_profile', 'follower_id', 'profile_id')->withTimestamps();}另请记住,这是一个many to many关系,因此在迁移中您不需要$table->bigIncrements('id');,但您必须以这种方式指定主键:public function up(){    Schema::create('profile_profile', function (Blueprint $table) {        $table->unsignedBigInteger('profile_id');        $table->unsignedBigInteger('follower');        $table->timestamps();        $table->primary(['profile_id', 'follower_id']);        $table->foreign('follower_id')->references('id')->on('profiles');        $table->foreign('profile_id')->references('id')->on('profiles');    });}
打开App,查看更多内容
随时随地看视频慕课网APP