Laravel:将同一模型上的两个字段关联起来


Laravel: associate two fields on same model

我开始对Laravel做同样的事情,我真的很喜欢模型已经准备好供您查询的方式,但是在这种情况下我发现了一些问题。

我为一个非常简单的消息传递系统创建了一个模型:

字段包括:

id [int]                  id message
id_user_from [int]        id sender user
id_user_to [int]          id recipient user
cnt [text]                content of message

我想在id_user_from和用户(Laravel 上的标准)和id_user_to(相同)之间添加关系。

我能够使用 id_user_from OR id_user_to 创建单个关系,但不能同时创建两者。

只需创建 2 个关系。

public function toUser(){
    return $this->belongsTo('User', 'id_user_to');
}
public function fromUser(){
    return $this->belongsTo('User', 'id_user_from');
}