How can put a MYSQL sentence in laravel:

SELECT Code_tank, temperature, salinity, PH, parameters.created_at as created_at FROM parameters WHERE id IN (SELECT MAX(id) FROM parameters group by code_Tank) ORDER BY code_tank ASC;

I have been trying to put this SQL sentence in laravel but could not, this is the code with that i was trying:

$testMonitor= DB::table('parameters')
    ->select('code_Tank', 'salinity', 'PH', 'temperature', 
    DB::raw('parameters.created_at AS created_at'))
    ->whereIn('id', DB::raw('SELECT MAX(id) FROM parameters group by code_Tank'))
    ->orderby('code_Tank', 'asc')->get();

And this is the error, I assumed that one of the parameters in WHEREIN must be an array but I can't think of any other way to accommodate the SQL statement in laravel, please if you could help me

TypeError: Argument 1 passed to Illuminate/Database/Query/Builder::cleanBindings() must be of the type array, object given, called in C:/laragon/www/SoftwareOzimandias/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php on line 907

Upvotes: 0

Views: 81

Answers (1)

TsaiKoga
TsaiKoga

Reputation: 13394

DB::Raw() will return an object as the second parameter for whereIn, but whereIn want to take the parameter that is array.

You can use closure, check the where-clauses reference:

DB::table('parameters')->whereIn('id', function($query){
    $query->select(DB::raw('MAX(id)'))
              ->from('parameters')
              ->groupBy('code_Tank');
})->orderby('code_Tank', 'asc')
->select('code_Tank', 'salinity', 'PH', 'temperature', 
    DB::raw('parameters.created_at AS created_at'))
->get();

Upvotes: 1

Related Questions