lightning_missile
lightning_missile

Reputation: 2992

Passing a raw SQL query to query builder on Laravel

Is there a way to initialize laravel's query builder with a raw query? Or at least to pass a full raw SQL query in an existing instance? Something like this:

$rawSQL = "select * from table ...";
$builder = DB::query($rawSQL); // returns a query builder instance
$builder->where(...); // like a normal ->where method in query builder

I have tried DB::select, but it returns an array, not a query builder instance that can be updated by more queries.

Upvotes: 0

Views: 1175

Answers (2)

Mike
Mike

Reputation: 423

You can try Builder::fromRaw, but note the syntax: it doesn't contain any 'select * from ...' - this would be added automatically:

DB::query()->fromRaw('users')->get();

Upvotes: 1

shaedrich
shaedrich

Reputation: 5735

You can use Builder::fromSub():

$rawSQL = "select * from table ...";
$builder = DB::query();
$builder->fromSub($rawSQL);
$builder->where(...); // like a normal ->where method in query builder

Upvotes: 2

Related Questions