我有一个teacher模型,并且teacher与student模型之间存在belongToMany关系。
我想要利用一个更高阶的消息函数来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关系实例。
如何使用具有Laravel雄辩关系的高阶消息?
发布于 2019-04-13 00:31:36
颠倒逻辑。
$teacherIds = Teacher::limit(5)->pluck('id')->toArray();
$student = Student::first();
$student->teachers()->sync($teacherIds);https://stackoverflow.com/questions/55654850
复制相似问题