1

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

Kendall
  • 5,065
  • 10
  • 45
  • 70
  • 1
    How about creating a thread model, where each thread can have many messages and messages belong to a single thread. – tam5 Dec 15 '16 at 23:01
  • @tam was thinking the same thing. Was wondering if i should create a pivot table and work my way backwords using `belongsToMany` had to jump off of it for a while but will post findings soon – Kendall Dec 16 '16 at 13:29

1 Answers1

1

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?

Community
  • 1
  • 1
Kendall
  • 5,065
  • 10
  • 45
  • 70