1 回答

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');
});
}
- 1 回答
- 0 關注
- 108 瀏覽
添加回答
舉報