Laravel - 2xHasMany Relate to another table

I have a table Messages

with columns fromandto

This corresponds to some users in the Users table.

So I need something like (hasMany relationship in user model - hasMany messages)

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

But there are two results, and the second is the Unreachable operator. So, how to manage many relationships when there are more than one?

+4
source share
2 answers

Create a second relation:

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

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

At first you cannot use 2 return like this

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

It is better if you divide it into 2 methods as follows:

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

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

Source: https://habr.com/ru/post/1682732/


All Articles