Actually found it a lot simpler than thought.
Given these models:
class User extends \Eloquent {
public function posts()
{
return $this->hasMany('Post');
}
public function comments()
{
return $this->hasManyThrough('Comment', 'Post');
}
}
class Post extends \Eloquent {
public function user()
{
return $this->belongsTo('User');
}
public function comments()
{
return $this->hasMany('Comment');
}
}
class Comment extends \Eloquent {
public function post()
{
return $this->belongsTo('Post');
}
}
We can then fetch a user that has a given post like so:
$userId = 2; $postId = 5;
$user = User::with(['comments' => function($q) use($postId) { $q->where('post_id', $postId); }])->find($userId);
This won't work when using get() as it DOES NOT constrain the users to only those related to the given post. But this is OK since we are only interested in a single post of post_id $postId. Since a post belongsTo one and only one user, we needn't worry about the other users. We could therefore use find() or first() to get the actual results.
Also, the 'middle' relationship i.e. 'post' is automatically returned and we can get it by doing the following without having to use an extra 'with' as suggested in previous answer:
var_dump($user->posts);