Question

I'm currenty making a forum in Laravel, just for the sake of learning, but I can't get my relations working well.

I have a Thread, Post and User model.

I've tried the following:

class User {
    public function thread() {
        return $this->hasMany('Thread');
    }

    public function post() {
        return $this->hasManyThrough('Thread', 'Post');
    }
}


class Thread {

    public function post() {
        return $this->hasMany('Post');
    }

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

class Post {

     public function thread() {
        return $this->belongsTo('Thread');
     }

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

With this method I can get a specific thread, and the posts that belong in it. But I can't grab the user who has posted the post in the thread.

I hope my problem is clear enough for you. Any help would really be appreciated.

Was it helpful?

Solution

For clarity I suggest you name your relations singular for hasOne/belongsTo and plural for belongsToMany/hasMany

so on the User and Thread it will be:

public function posts() ...

Now, this is in wrong order:

class User {
  public function posts() {
    // return $this->hasManyThrough('Thread', 'Post'); // wrong, change to:
    return $this->hasManyThrough('Post', 'Thread');
  }
}

Apart from that your relations look good, so you should be able to do this:

$thread = Thread::with('posts.user')->find($threadId); // eager load relations
$thread->posts; // Eloquent Collection of Post models
foreach ($thread->posts as $post)
{
  $post->user; // author's User model
}

And by the way you can always have a look at the Laravel.io source: https://github.com/LaravelIO/laravel.io/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top