Reputation: 5205
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
Upvotes: 2
Views: 76
Reputation: 2911
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();
}
Upvotes: 1
Reputation: 34924
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);
Upvotes: 2
Reputation: 163968
You need to add get()
to the query to execute it:
DB::table('instruments')->(....)->get()->toArray();
Upvotes: 3