I am having the following query:
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
Below is my eloquent translation:
$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();
I would like to get the result as array back so i used toArray()
:
However, I am getting the following error:
In Builder.php line 2461:
Call to undefined method Illuminate\Database\Query\Builder::toArray()
Any suggestions why this is the case?
I appreciate your replies!
UPDATE:
After adding ->get()
to the end of my query, I get the following error:
In Grammar.php line 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
您需要将get()
添加到查询中才能执行它:
DB::table('instruments')->(....)->get()->toArray();
After getting query builder result,
$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();
Either use, (array) $result
$overviewArray = (array) $result;
Or json_decode(json_encode(...))
to convert in array
$overviewArray = json_decode(json_encode($result), true);
toArray()
shows exception when no record found based on the query(Single record). For this just handle exception before using toArray()
Example:
$data = DB::table('instruments')->(....)->first();
if($data!=null){
$arrayData = $data->toArray();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.