laravel - Laravel 在没有 foreach 的情况下获取集合的 id
问题描述
我的代码目前如下所示:
foreach ($things as $thing) {
$ids[] = $thing->id;
}
dd(Other::whereIn('thing_id', $ids)->get());
事物模型有很多 Other
public function others()
{
return $this->hasMany(Other::class);
}
它正在工作,但是我可以在不使用 foreach 的情况下实现此功能吗?对我来说似乎并不干净。我试图把整个收藏品放在这样的地方:
dd(Other::whereIn('thing_id', $things)->get());
但这仅在 id 为 1 的地方返回。
我正在寻找清理此代码的帮助,任何帮助表示赞赏。
解决方案
有一个功能叫做“pluck”
您可以将其应用于集合,如下所示
$collection->pluck('id');
更多可以在文档上看到
推荐阅读
- statistics - 对变量的每个类别分别运行分析
- javascript - 如何映射函数和文本 ReactJs
- reactjs - 如何在 Redux 中制作受控输入组件?
- bower - bash: bower: NVM 找不到命令
- javascript - 合并2个对象在js中包括他们的孩子
- html - 如何根据使用 CSS 对嵌套输入的关注来更改分隔 div 的颜色?
- html - IE 搜索文本功能不适用于从 AJAX 生成的代码
- python - 使用 PIL/Pillow 制作 GIF
- java - 直接在其他 json 对象中获取特定的嵌套 json 对象
- validation - 如何在 Blazor 中实现自定义验证