为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
慕沐林林 2022-06-11 18:29:23
我正在尝试在 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 会与命名约定冲突吗?
查看完整描述

1 回答

?
幕布斯6054654

TA贡献1876条经验 获得超7个赞

对于这种情况,您无法遵循命名约定:您必须按照您的建议为第二个外键指定不同的名称。

这不会导致任何问题,但是当您在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');

    });

}


查看完整回答
反对 回复 2022-06-11
  • 1 回答
  • 0 关注
  • 136 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号