Created
March 23, 2014 22:27
-
-
Save Kindari/9730812 to your computer and use it in GitHub Desktop.
Post with X comments per post
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Post extends Eloquent | |
{ | |
public function comments() | |
{ | |
return $this->hasMany('Comment'); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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