Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to map a raw query to a Model

I have a complex raw SQL query that I don't want to retro-convert to query builder. Is there a way to map the result of the query to a model?

In short, I have this kind of query:

SELECT users.* FROM users
WHERE exists (super_long_raw_query)
AND many_more_raw_where_clauses
ORDER BY something_complex
etc;

It only returns columns from one Model (from a table corresponding to a model).

It would be terrible and not readable to convert it to a "Laravel Query Builder" query:

User::where(/* ... */)
    ->whereExists(function() { /* super complex callback */ } )
    ->etc(/* ... */)

The raw query is easier (in this specific case) to read.

Is there a way to map a raw query to a model? (assuming it only returns the columns of a specific model)

Side note: It's a raw query that uses query parameters (?, :something) because I don't want injections.

like image 694
rap-2-h Avatar asked Apr 04 '18 09:04

rap-2-h


People also ask

How to execute raw SQL queries in django?

Django gives you two ways of performing raw SQL queries: you can use Manager. raw() to perform raw queries and return model instances, or you can avoid the model layer entirely and execute custom SQL directly. Explore the ORM before using raw SQL!

What is raw query?

On the other hand, RawQuery serves as an escape hatch where you can build your own SQL query at runtime but still use Room to convert it into objects. RawQuery methods must return a non-void type. If you want to execute a raw query that does not return any value, use RoomDatabase#query methods.

What is raw SQL?

Raw SQL, sometimes also called native SQL, is the most basic, most low-level form of database interaction. You tell the database what to do in the language of the database. Most developers should know basics of SQL. This means how to CREATE tables and views, how to SELECT and JOIN data, how to UPDATE and DELETE data.


2 Answers

Use fromQuery()

$query = \Illuminate\Support\Facades\DB::raw('select * from users');
$users = \App\User::fromQuery($query, []);
like image 63
Sohel0415 Avatar answered Sep 28 '22 15:09

Sohel0415


You could use hydrate method:

$users = User::hydrate(
    DB::select('super_complex_query_with_params', [$params])
);

See: https://laravel.com/api/5.6/Illuminate/Database/Eloquent/Builder.html#method_hydrate

like image 22
rap-2-h Avatar answered Sep 28 '22 15:09

rap-2-h