通过 laravel DB class 从 DB 获取结果,数组的每个索引是结果 id
Getting result from DB by laravel DB class which the each index of array is the result id
伙计们,我正试图通过 laravel 5.5 从我的数据库中获取结果。
如果我 运行 这个代码:
DB::table('comments')->get()
它将return 一个包含stdClasses 的数组。
现在我希望数组中每个 stdClass 的键(索引)是 stdClass 的 ID。
我只想知道 laravel 有这个功能吗?
更新:
这是 returned 数组,例如:
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => stdClass Object
(
[id] => 7
....
)
[1] => stdClass Object
(
[id] => 8
....
)
[2] => stdClass Object
(
[id] => 9
....
)
)
)
注意上面的代码。我想要 7,8,9 而不是 0,1,2 。
检查这个,https://laravel.com/docs/5.6/collections#method-pluck
DB::table('comments')->get()->pluck('id');
编辑 看来你想通过 id 键控你的数组。
有这个方法https://laravel.com/docs/5.6/collections#method-keyby,
所以它看起来像
DB::table('comments')->get()->keyBy('id')->all();
您可以将此代码用于 2 列(例如 'title' 和 'id'):
DB::table('comments')->get()->pluck('title', 'id');
tnx Sérgio Reis 但你不需要 ->all();
只是:
DB::table('comments')->get()->keyBy('id');
伙计们,我正试图通过 laravel 5.5 从我的数据库中获取结果。 如果我 运行 这个代码:
DB::table('comments')->get()
它将return 一个包含stdClasses 的数组。 现在我希望数组中每个 stdClass 的键(索引)是 stdClass 的 ID。
我只想知道 laravel 有这个功能吗?
更新: 这是 returned 数组,例如:
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => stdClass Object
(
[id] => 7
....
)
[1] => stdClass Object
(
[id] => 8
....
)
[2] => stdClass Object
(
[id] => 9
....
)
)
)
注意上面的代码。我想要 7,8,9 而不是 0,1,2 。
检查这个,https://laravel.com/docs/5.6/collections#method-pluck
DB::table('comments')->get()->pluck('id');
编辑 看来你想通过 id 键控你的数组。
有这个方法https://laravel.com/docs/5.6/collections#method-keyby, 所以它看起来像
DB::table('comments')->get()->keyBy('id')->all();
您可以将此代码用于 2 列(例如 'title' 和 'id'):
DB::table('comments')->get()->pluck('title', 'id');
tnx Sérgio Reis 但你不需要 ->all();
只是:
DB::table('comments')->get()->keyBy('id');