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 关注
- 136 浏览
添加回答
举报
