亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 108 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號