2015-10-04 75 views
0

我设置UserCreditLaravel - 两列,在另一个表的关系,以同一列

用户

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(),雄辩是无法“绑定“到我的User模型。

我该如何解决这个问题?

回答

3

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

$credit->recipient->name 

你不能访问用户表,因为laravel将加载领域。并且该字段没有名为的属性。

早些时候关系是用户()它的工作。因此,请考虑为用户找到合适的姓名,例如credit_recipient()

相关问题