Reputation: 10219
I'm using Laravel 3.x.
Post::with(
array('blogs' => function($query) {
$query->where('user_id', '=', Auth::user()->id);
} ))->get();
How can I paginate the posts?
Upvotes: 1
Views: 747
Reputation: 10219
This is the solution I came up with. A user can have many blogs and a post can belong to many blogs.
/**
* Get all posts by a user for all blogs.
* @return paginated posts.
*/
public static function get_posts_for_user($user_id, $limit)
{
return Post::left_join('blog_post', 'posts.id', '=', 'blog_post.post_id')
->join('blogs', 'blogs.id', '=', 'blog_post.blog_id')
->where('blogs.user_id', '=', $user_id)
->paginate($limit);
}
Upvotes: 1
Reputation: 5773
FakeHeal,
Supposing that $user->has_one('blog')
, you can simply use Laravel magic relationship getter:
$user = Auth::user();
$user->blog->posts();
If that's not the case and user->has_many('blog')
, you need to use JOIN to retrieve all posts made to all of that user blogs.
$user = Auth::user();
$posts = Posts::join('blogs', 'blogs.id', '=', 'posts.blog_id')
->where('blogs.user_id', '=', $user->id)
->get('posts.*');
Upvotes: 1
Reputation: 9280
From the feedback above it seems that eager loading isn't what you are looking for. Try this.
Post::where( 'user_id', '=', Auth::user()->id )->paginate( 10 );
Or you could add a posts method to the User model.
public function posts()
{
return $this->has_many( 'Post' );
}
Then use that to get the users posts.
Auth::user()->posts()->paginate( 10 );
Upvotes: 1