Skip to content

Instantly share code, notes, and snippets.

@Kindari
Created March 23, 2014 22:27
Show Gist options
  • Save Kindari/9730812 to your computer and use it in GitHub Desktop.
Save Kindari/9730812 to your computer and use it in GitHub Desktop.
Post with X comments per post
<?php
class Comment extends Eloquent
{
public function post()
{
return $this->belongsTo('Post');
}
public function scopePerPost($query, $limit) {
$ids = Cache::remember('paged_comment_ids', 10, function() use ($limit) {
$ids = array();
foreach(Comment::lists('post_id', 'id') as $comment_id => $post_id)
{
if ( ! array_key_exists($post_id, $ids) ) $ids[$post_id] = array();
if ( count($ids[$post_id]) < $limit ) $ids[$post_id][] = $comment_id;
}
return array_unique( array_flatten($ids) );
});
return $query->whereIn('id', $ids);
}
}
<?php
class Post extends Eloquent
{
public function comments()
{
return $this->hasMany('Comment');
}
}
<?php
Route::get('comments', function() { return Comment::with('post')->get(); });
Route::get('posts', function() { return Post::with('comments')->get(); });
Route::get('page', function() {
return Post::with(array('comments' => function($query) {
$query->perPost(3);
}))->get();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment