Kendall
Kendall

Reputation: 5255

Recursive Eloquent Models

I have a Message::class for which I want to get thread messages for each particular message.

how can I recursively fetch messages and messages of messages etc. etc. using Laravel and Eloquent::hasMany

So far I tried setting up a recursive on the hasMany()

public function replys()
{
  return $this->hasMany(Message::class, 'reply_to', 'id');
}

public function replies()
{
    $r = $this->replys;
    if(count($r->get('replys')) > 0){
      foreach($r->get('replys') as $reply) {
        $r->push(Message::create($reply)->replies());
      }
    }

    return $r;
}

But I seem to be missing the mark. At the moment I'm trying to see if I can use a pivot table and reference belongsToMany . Will let yo know how things progress

Upvotes: 1

Views: 2012

Answers (1)

Kendall
Kendall

Reputation: 5255

Research led me to this thread that suggested how to get recursive records via hasMany

thus

public function replys()
{
  return $this->hasMany(Message::class, 'reply_to', 'id');
}

public function replies()
{
  return $this->replys()->with('replies');
}

Did not think it would be this easy however, I was hoping that I could have kept it simple without having to devise a complex raw query statement.

My question now is how does this recursive method stand up to large data sets?

Upvotes: 2

Related Questions