我尝试在用户和债券之间建立关系。一个债券总是包含两个用户(债务人,债权人)。
最后,如果我致电$bond->debtor
或$bond->creditor
用户模型:
public function bonds()
{
return $this->hasMany(Bond::class);
}
债券模型:
protected $fillable = ['description', 'amount', 'debtor_id', 'creditor_id'];
public function debtor()
{
return $this->belongsToMany(User::class, 'bond_user', 'debtor_id', 'user_id');
}
public function creditor()
{
return $this->belongsToMany(User::class, 'bond_user', 'creditor_id', 'user_id');
}
两次迁移:
Schema::create('bonds', function (Blueprint $table) {
$table->increments('id');
$table->text('description');
$table->float('amount', 8, 2);
$table->integer('debtor_id');
$table->integer('creditor_id');
$table->timestamps();
});
Schema::create('bond_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('debtor_id');
$table->integer('creditor_id');
$table->timestamps();
});
每当我打电话的时候。 $bond->debtor
我得到一个整数而不是用户模型。
更新
我找到了解决方案:
用户模型:
public function bond_debtor()
{
return $this->hasMany(Bond::class, 'debtor_id');
}
public function bond_creditor()
{
return $this->hasMany(Bond::class, 'creditor_id');
}
债券模型:
public function debtor()
{
return $this->belongsTo(User::class, 'debtor_id');
}
public function creditor()
{
return $this->belongsTo(User::class, 'creditor_id');
}
答案 0 :(得分:0)
设置关系时,您需要
将参考列的字段类型设置为integer
和unsigned
$table->integer('debtor_id')->unsigned();
$table->integer('creditor_id')->unsigned();
使用foreign
Table
方法设置关系:
$table->foreign('debtor_id')
->references('id')->on('user');
$table->foreign('creditor_id')
->references('id')->on('user');