hasManyThrough on same models

343 Views Asked by At

I have two classes User and Message,

I'm trying to get the replies to the user's messages from the user class thus

in the user class

public function replies()
{
   return $this->messages->replies; 
} 

However this doesn't seem to work so I'm trying the hasManyThrough operation

public function replies() 
{
    return $this->hasManyThrough(Message::class,Message:class,'reply_id','user_id','id');
}

This doesn't work either because of a unique table issue

What's the best way to perform this operation?

Should I just use a raw get?

public function replies()
{
    return Message::whereIn('reply_id', $this->messages->pluck('id'))->get() 
}

Bare in mind I may also want to perform pagination and ordering features

1

There are 1 best solutions below

1
On

Why are you using hasManyThrough() when it is only a one to many relationship?

What I would do in your case is within the User object use $this->hasMany('\App\Models\Message').

Then within the Message object use $this->belongsTo('\App\Models\User')

Then from your User object you would be able to do $user->messages->replies

https://laravel.com/docs/5.3/eloquent-relationships#one-to-many

Example

The User object:

class User extends Model {

    public function messages() {
         return $this->hasMany('App\Models\Message');
    }
}

The Message object:

class Message extends Model {

    public function user() {
         return $this->belongsTo('App\Models\User');
    }
}

Then within a controller function of some kind for example you can do:

$user = User::with('messages')->findOrFail(1);

Which would return the User object with the messages which is it associated with.

So then you could do:

$user->messages->replies