1

I have the following models.

class User extends Eloquent {
  public function comments() {
    return $this->hasMany('Comment');
  }
}

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

For the sake of this example, a user could have 1,000s of comments. I am trying to limit them to just the first 10. I have tried doing it in the User model via

class User extends Eloquent {
  public function comments() {
    return $this->hasMany('Comment')->take(10);
  }
}

and via UserController via closures

$users = User::where('post_id', $post_id)->with([
  'comments' => function($q) {
     $q->take(10);
   }
]);

Both methods seem to only work on the first record of the result. Is there a better way to handle this?

Jarek Tkaczyk
  • 78,987
  • 25
  • 159
  • 157
Don Boots
  • 2,028
  • 2
  • 18
  • 26
  • You can't use `limit` (and `take` for it's just its alias) for such thing. Read this http://softonsofa.com/tweaking-eloquent-relations-how-to-get-n-related-models-per-parent/ – Jarek Tkaczyk Sep 23 '14 at 21:29
  • 1
    This seems like quite the oversight on Laravel's part for a pretty basic piece of functionality. Looks like I may have to change my code to query each User's comments individually? – Don Boots Sep 24 '14 at 13:36
  • I don't think it's pretty basic piece of functionality in terms of the db (if you find linked way that way). You can of course query each users comments if you like. Otherwise you have a ready to use solution in that article. – Jarek Tkaczyk Sep 24 '14 at 14:24

0 Answers0