我使用此查询将 ids 获取到变量中:
$ids = DB::table('note_user')->select('note_id')->where('user_id', $user_id)->get('note_id');
由于我有两个笔记属于一个用户,所以我得到
[{"note_id":1},{"note_id":2}]
这似乎是一个集合数组,每个 Laravel collection method我尝试应用它会返回错误。例如,
$flattened = $ids->flatMap(function ($values) {
return $values;
});
返回
Fatal error: Call to a member function flatMap() on array
有什么办法可以转
[{"note_id":1},{"note_id":2}]
进入
[1, 2]
?
最佳答案
最简单的解决方案是使用 pluck
来代替。
$ids = DB::table('note_user')->select('note_id')->where('user_id', $user_id)->pluck('note_id');
https://laravel.com/api/5.1/Illuminate/Database/Query/Builder.html#method_pluck
这仅返回您想要的整数数组。
关于php - Laravel:如何从一组集合中创建一个集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37084219/