【问题标题】:Laravel - two columns with relationship to the same column in another tableLaravel - 两列与另一个表中的同一列有关系
【发布时间】:2015-10-04 21:07:36
【问题描述】:

我在UserCredit之间建立了一对多的Eloquent关系

用户

id | name

信用

id | recipient | author | amount

在哪里

recipientuser.id

authoruser.id

在 Laravel 中,recipient 的关系已建立:

class Credit extends Model {
    public function user() {
        return $this->belongsTo('App\User', 'recipient');
    }
}

但是我该如何添加author 的关系呢?

我试过了:

class Credit extends Model {
    public function recipient() {
        return $this->belongsTo('App\User', 'recipient');
    }
    public function author() {
        return $this->belongsTo('App\User', 'author');
    }
}

即我把user()改成了两个函数:recipient()author()

但我得到了Trying to get property of non-object,我认为这意味着使用recipient()author(),Eloquent 无法将其“绑定”到我的User 模型。

我该如何解决这个问题?

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    问题是您有一个名为收件人的字段和一个共享相同名称的关系。考虑重命名其中一个,这是因为 laravel 将使用该字段,因此如果你这样做

    $credit->recipient->name 
    

    您无法访问用户表,因为 laravel 将加载该字段。并且该字段没有名为 name 的属性。

    早先,当关系是 user() 时,它起作用了。因此,请考虑为用户找到合适的名称,例如 credit_recipient()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-21
      • 2015-10-23
      • 2021-09-10
      • 2023-03-11
      • 2018-06-13
      • 1970-01-01
      • 2023-03-06
      相关资源
      最近更新 更多