【问题标题】:Expected type 'array'. Found 'Illuminate\Support\Collection' Laravel Query Builder预期类型“数组”。找到 'Illuminate\Support\Collection' Laravel 查询生成器
【发布时间】:2021-11-29 11:25:35
【问题描述】:

我在我的 Laravel 8.54 项目中使用原始 SQL 语句,例如:

$data = DB::select("SELECT * FROM ..WHERE..= '$number' AND.. like '$SelectedMonth%' ORDER BY ..ASC");

然后我使用 Laravel Query Builder 将它们转换为:

$data = DB::table("..")
                        ->select("..")
                        ->where("..", "=", $number)
                        ->where("..", "like", $SelectedMonth.'%')
                        ->orderBy("..", "asc")
                        ->get();

在更改之前,SQL 查询返回了一个对象数组,我可以使用 Sort() 和其他一些函数。

现在我收到错误:sort(): Argument #1 ($array) must be of type array, Illuminate\\Support\\Collection givenExpected type 'array'. Found 'Illuminate\Support\Collection'

如何将给定的结果转换回数组?

谢谢

【问题讨论】:

    标签: sql laravel eloquent


    【解决方案1】:

    get 方法返回一个包含查询结果的 Illuminate\Support\Collection 实例,其中每个结果都是 PHP stdClass 对象的一个​​实例。

    要将集合转换为数组,请使用toAttay() 方法。

    https://laravel.com/docs/8.x/collections#method-toarray

    您也可以使用sortBy() 方法对集合进行排序。

    https://laravel.com/docs/8.x/collections#method-sortby

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-15
      • 2019-11-29
      • 2019-06-05
      • 2021-05-27
      • 2021-09-27
      • 2019-12-10
      • 2017-02-16
      • 1970-01-01
      相关资源
      最近更新 更多