我有一个具有Classroom
关系的模型belongsToMany
。我希望它的孩子的顺序由模型上已经存在的ID数组急切地确定,例如student_ids
有[5,1,7,9,2]
。
换句话说,每当我收到Classroom
时,都应始终按此顺序选择其Students
。
public function students()
{
return $this->belongsToMany(Student::class)->withTimestamps();
}
我尝试了sortBy('student_ids')
和orderBy('student_ids')
都无法使用-但我已经设法通过在我的Classroom
中使用类似的方式对它们进行了排序控制器:
public function sortedStudents($ids)
{
return $this->students()->sortBy(function ($student) use ($ids) {
return array_search($student->id, $ids);
});
}
这可行,但是我需要在事实之后传递ids
。我希望在关系本身中“默认”处理它。
谢谢。 ?
答案 0 :(得分:2)
您可以使用orderByRaw
和FIELD()
方法按特定值顺序进行排序:
public function students()
{
return $this->belongsToMany(Student::class)->withTimestamps()->orderByRaw("FIELD(id, 5,1,7,9,2)");
}
答案 1 :(得分:1)
您可以使用withPivot
方法来添加学生ID,然后可以进行订购:
public function students()
{
return $this->belongsToMany(Student::class)->withPivot('student_id')->orderBy('classroom_student.student_id');
}
在此示例中,我假设您的数据透视表名为classroom_student
。