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
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:
The Message object:
Then within a controller function of some kind for example you can do:
Which would return the User object with the messages which is it associated with.
So then you could do: