如何在Eloquent中使用高阶消息?

时间:2019-04-12 15:20:50

标签: laravel laravel-5 eloquent

我有一个teacher模型,而teacherbelongToMany模型具有student关系。

我想利用高阶消息功能将sync student传播给许多teachers.

通常,我会执行以下操作:

$teachers = Teacher::limit(5)->get();
$student = Student::first();

$teachers->each(function($teacher) use ($student) {
    $teacher->students()->sync($student)
});

使用高阶函数,我应该可以:

// Throws error BadMethodCallException: Method Illuminate\Database\Eloquent\Collection::sync does not exist.
$teachers->each->students()->sync($student);

不幸的是,由于在类HigherOrderCollectionProxy中定义的高阶消息是如何工作的,因此将执行关系students(),返回教师拥有的所有学生的集合,而不是返回belongsToMany关系实例。 / p>

如何在Laravel雄辩的关系中使用高阶消息?

1 个答案:

答案 0 :(得分:1)

颠倒逻辑。

$teacherIds = Teacher::limit(5)->pluck('id')->toArray();
$student = Student::first();

$student->teachers()->sync($teacherIds);