Laravel: hasMany() with take() only working on first result

流过昼夜 提交于 2019-12-13 00:44:52

问题


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?

来源:https://stackoverflow.com/questions/26003841/laravel-hasmany-with-take-only-working-on-first-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!