【问题标题】:Getting result from DB by laravel DB class which the each index of array is the result id通过 laravel DB 类从 DB 中获取结果,其中数组的每个索引都是结果 id
【发布时间】:2018-08-20 09:28:38
【问题描述】:

伙计们,我正在尝试通过 laravel 5.5 从我的数据库中获取结果。 如果我运行这段代码:

DB::table('comments')->get()

它将返回一个包含 stdClasses 的数组。 现在我希望数组中每个 stdClass 的键(索引)是 stdClass 的 ID。

我只想知道laravel有这个功能吗?

更新: 这是返回的数组,例如:

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 。

【问题讨论】:

  • Laravel 拥有所有的功能。 Laravel 值得称赞。
  • @Amarnasan 谢谢你告诉我,但我的句子意味着为 laravel 建议方法。

标签: php laravel laravel-5.5


【解决方案1】:

检查一下,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】:

您可以将此代码用于 2 列(例如 'title' 和 'id'):

DB::table('comments')->get()->pluck('title', 'id');

tnx Sérgio Reis 但你不需要 ->all();

只是:

DB::table('comments')->get()->keyBy('id');

【讨论】:

    猜你喜欢
    • 2020-08-21
    • 2020-07-05
    • 2016-07-12
    • 1970-01-01
    • 2021-03-26
    • 2021-06-16
    • 2018-05-07
    • 1970-01-01
    • 2019-04-15
    相关资源
    最近更新 更多