php - Laravel:如何从一组集合中创建一个集合?

标签 php mysql laravel

我使用此查询将 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/

相关文章:

mysql - 在sql中跨多个列插入单个值

c# - 连接到网络上的 MySQL 数据库

sql - 在两列上创建索引以检查日期是否介于这两个列之间

laravel - 设置 Laravel 迁移的默认值

javascript - 如何在不使用 Google 文档或任何其他查看器平台的情况下在网页中嵌入文档 .docx、.doc 和 .xlsx、.xls

php - 将参数传递给 cakephp 3.x 中的自定义 find 方法

javascript - 将 mysql_fetch_array 中的 php 数据保存为脚本变量

php - 代码点火器 : insert data in database

php preg_replace 匹配

javascript - Laravel 5.6 - 使用 laravel-mix 拆分 vuejs 代码