Laravel - 两列,在另一个表的关系,以同一列
问题描述:
我设置User
和Credit
Laravel - 两列,在另一个表的关系,以同一列
用户
id | name
信用之间存在一个一对多的雄辩关系
id | recipient | author | amount
其中
recipient
是user.id
author
是user.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()
,雄辩是无法“绑定“到我的User
模型。
我该如何解决这个问题?
答
问题是您有一个名为收件人的字段和一个关系共享相同的名称。考虑重命名他们这一个是因为laravel将使用领域,而不是因此,如果你这样做
$credit->recipient->name
你不能访问用户表,因为laravel将加载领域。并且该字段没有名为的属性。
早些时候关系是用户()它的工作。因此,请考虑为用户找到合适的姓名,例如credit_recipient()