将查询结果作为数组返回

问题描述 投票:2回答:3

我有以下查询:

            SELECT *
            FROM instruments
            LEFT join financials on instruments.id=financials.instruments_id
            WHERE financials.id IN
            ( SELECT MAX(financials.id)
            FROM financials
            GROUP BY financials.instruments_id )
            ORDER BY instruments.id ASC

以下是我雄辩的翻译:

$overviewArray = DB::table('instruments')
    ->leftJoin('financials', 'instruments.id', '=', 'financials.instruments_id')
    ->whereIn('financials.id', DB::raw('SELECT MAX(financials.id)
    FROM financials
    GROUP BY financials.instruments_id )
    ORDER BY instruments.id ASC'))->toArray();

我想把结果作为数组返回所以我使用toArray()

但是,我收到以下错误:

In Builder.php line 2461:

  Call to undefined method Illuminate\Database\Query\Builder::toArray()

有什么建议为什么会这样?

感谢您的回复!

更新:

在我的查询结束时添加->get()后,我收到以下错误:

在Grammar.php第135行:

  Type error: Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, object given, called
  in C:\Users\admin\Desktop\Coding Projects\demo\vendor\laravel\framework\src\Illuminate\Database\Query\Gramm
  ars\Grammar.php on line 250
php laravel laravel-5 eloquent
3个回答
3
投票

您需要将get()添加到查询中以执行它:

DB::table('instruments')->(....)->get()->toArray();

2
投票

获取查询构建器结果后,

$result = DB::table('instruments as i')
    ->leftJoin('financials as f', 'i.id', '=', 'f.instruments_id')
    ->whereIn('f.id', DB::raw('SELECT MAX(f.id) FROM financials as fs GROUP BY fs.instruments_id'))
    ->orderBy('i.id')
    ->get();

要么使用,(array) $result

$overviewArray = (array) $result;

或者json_decode(json_encode(...))转换为数组

$overviewArray = json_decode(json_encode($result), true);

1
投票

当没有根据查询找到记录时,toArray()显示异常(单记录)。为此,在使用toArray()之前只处理异常

例:

$data = DB::table('instruments')->(....)->first();
if($data!=null){
 $arrayData = $data->toArray();
}
© www.soinside.com 2019 - 2024. All rights reserved.