引用自docs:
如果您想自定义关系的键,可以将它们作为第三个和第四个参数传递给 hasManyThrough 方法。第三个参数是中间模型的外键名称,第四个参数是最终模型的外键名称。
您应该能够按照那里的描述传递您的自定义外键列名称。
--编辑:
经过一番思考,我认为hasManyThrough 不足以实现您想要实现的目标(至少在问题中提供的信息很少的情况下)。相反,belongsToMany 应该这样做:
在全新的 Laravel 5.2 安装中,我为此类数据透视表创建了一个迁移(灵感来自另一个 post):
public function up()
{
Schema::create('follows', function (Blueprint $table) {
// Edit 2 without an incremental id
// $table->increments('id');
$table->integer('follower_id')->unsigned();
$table->integer('followee_id')->unsigned();
$table->foreign('follower_id')->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('followee_id')->references('id')
->on('users')
->onDelete('cascade');
// Edit 2: with primary and unique constraint
$table->primary(['follower_id', 'followee_id']);
$table->unique(['follower_id', 'followee_id']);
});
}
并且在 App\User 模型中
public function followers()
{
return $this->belongsToMany(
self::class,
'follows',
'followee_id',
'follower_id'
);
}
public function followees()
{
return $this->belongsToMany(
self::class,
'follows',
'follower_id',
'followee_id'
);
}
然后,在播种一些用户和枢轴关系之后,这对我有用:
$user = User::first();
// user is followed by
echo json_encode($user->followers()->get());
// user is following
echo json_encode($user->followees()->get());
在这个(简单)示例的第一个版本中,有两个主键:“用户”上的“id”和“关注”上的“id”,即约定的默认值。您可以像 protected $primaryKey = 'user_id'; 那样覆盖模型中的 pk。 SO上有一个post。
现在数据透视表有一个复合键,它必须是唯一的,我猜这就是 OP 的意图。
-- 编辑 2:
有了约束,您应该像这样添加关注者:
$user->followers()->sync([$anotherUser->id],false);
为了避免在复合键已经存在的情况下违反完整性约束。同步方式建议here。
希望这会有所帮助。