【问题标题】:Laravel Models & RelationshipsLaravel 模型和关系
【发布时间】:2016-03-21 03:11:33
【问题描述】:

我尝试在用户和债券之间建立关系。一张债券总是包含两个用户(债务人、债权人)。

最后,如果我调用$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');
}

【问题讨论】:

  • 你试过用 $bond->debtor() 代替 $bond->debtor 感觉它们会产生不同的结果。

标签: laravel eloquent models relationships


【解决方案1】:

设置关系时,需要

  1. 设置引用列的字段类型为integer和unsigned

    $table->integer('debtor_id')->unsigned();
    $table->integer('creditor_id')->unsigned();
    
  2. 用foreignTable方法设置关系:

    $table->foreign('debtor_id')
        ->references('id')->on('user');
    $table->foreign('creditor_id')
        ->references('id')->on('user');
    

【讨论】:

  • 没有你的建议我可以解决这个问题。这些是建立这种关系的最佳做法吗?
  • @Sebastian Guess 所以,这就是我学到的方法,直到现在都没有问题。
猜你喜欢
  • 1970-01-01
  • 2015-10-25
  • 1970-01-01
  • 2019-04-04
  • 1970-01-01
  • 2020-04-02
  • 2018-07-11
相关资源
最近更新 更多