首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Eloquent中使用高阶消息?

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

Stack Overflow用户
提问于 2019-04-12 23:20:50
回答 1查看 273关注 0票数 1

我有一个teacher模型,并且teacherstudent模型之间存在belongToMany关系。

我想要利用一个更高阶的消息函数来sync一个student到许多teachers.

通常我会做以下几件事:

代码语言:javascript
复制
$teachers = Teacher::limit(5)->get();
$student = Student::first();

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

对于高阶函数,我应该能够做到:

代码语言:javascript
复制
// Throws error BadMethodCallException: Method Illuminate\Database\Eloquent\Collection::sync does not exist.
$teachers->each->students()->sync($student);

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

如何使用具有Laravel雄辩关系的高阶消息?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-13 00:31:36

颠倒逻辑。

代码语言:javascript
复制
$teacherIds = Teacher::limit(5)->pluck('id')->toArray();
$student = Student::first();

$student->teachers()->sync($teacherIds);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55654850

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档