按ID数组对EmiratesToMany关系进行排序

时间:2020-02-10 05:59:01

标签: php laravel eloquent

我有一个具有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。我希望在关系本身中“默认”处理它。

谢谢。 ?

2 个答案:

答案 0 :(得分:2)

您可以使用orderByRawFIELD()方法按特定值顺序进行排序:

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