Home > OS >  Get only 3 records using with from many to many relationship Laravel
Get only 3 records using with from many to many relationship Laravel

Time:05-11

I'm using laravel 7 and I have 3 tables shown below. I want first three students data instead of all student. tables have many to many relationship.

  1. groups
  • id
  • name
  1. students
  • id
  • name
  1. group_student_pivot
  • group_id
  • student_id
  • created_at

I have below relationship in models

Groups model
public function students()
    {
        return $this->belongsToMany(Student::class,'group_student_pivot')->withPivot(['status'])->withTimestamps();
    }


Student model
public function groups()
    {
        return $this->belongsToMany(Group::class,'group_student_pivot')->withPivot(['status'])->withTimestamps();
    }
    
$groups = Group::whereIn('id',$groupIds)->with('students')->get();

In above query I want first 3 students data instead of all students.

CodePudding user response:

You can get 3 records like this:

$groups = Group::whereIn('id',$groupIds)->with('students', function($q){
                $q->take(3);
            })->get();

CodePudding user response:

You can use with and whereHas method

$groups = Group::with('students')->whereHas('students', function($q){
            $q->take(3);
        })->whereIn('id',$groupIds)->get();
  • Related