Laravel - 2xHasMany Relations另一张桌子

时间:2017-08-01 09:49:35

标签: php laravel eloquent

我有表Messages

fromto

这对应于表Users中的一些用户。

所以我需要类似(用户模型中的hasMany关系 - hasMany消息)

public function Messages()
    {
        return $this->hasMany('App\Models\Messages', 'from', 'id');
        return $this->hasMany('App\Models\Messages', 'to', 'id');
    }

但是有两个返回,第二个是无法到达的语句。 那么当有多个关系时,如何管理多个关系?

2 个答案:

答案 0 :(得分:3)

创建第二个关系:

public function messageRetrieved()
{
    return $this->hasMany('App\Models\Messages', 'from', 'id');
}

public function messageSend()
{
    return $this->hasMany('App\Models\Messages', 'to', 'id');
}

答案 1 :(得分:0)

首先你不能像这样使用2回报

public function Messages()
{
    return $this->hasMany('App\Models\Messages', 'from', 'id');
    return $this->hasMany('App\Models\Messages', 'to', 'id');
}

如果将它分成2个这样的方法会更好:

public function to()
{
    return $this->hasMany('App\Models\Messages', 'to', 'id');
}

public function from()
{
    return $this->hasMany('App\Models\Messages', 'from', 'id');
}
相关问题