[英]Get only 3 records using with from many to many relationship Laravel
我正在使用 laravel 7,下面显示了 3 个表。 我想要前三个学生的数据而不是所有学生。 表有多对多的关系。
我在模型中有以下关系
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();
在上面的查询中,我想要前 3 个学生数据而不是所有学生。
您可以获得 3 条这样的记录:
$groups = Group::whereIn('id',$groupIds)->with('students', function($q){
$q->take(3);
})->get();
您可以使用 with 和 whereHas 方法
$groups = Group::with('students')->whereHas('students', function($q){
$q->take(3);
})->whereIn('id',$groupIds)->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.