DEV Community

loading...

Discussion on: Laravel ORM vs Query Builder vs SQL: SPEED TEST!

Collapse
lito profile image
Lito • Edited

There are not difference between Query Builder and SQL query because Query Builder is only a query generator, and generate a string using an object is not a hard work. Both methods returns same result.

But ORM is more than a query builder, every database result is hydratated with the model, then you have a collection with 1000 Article models instead a collection of 1000 plain objects.

You can do same test with Query Builder and SQL with hydrate methods:

ORM

$articles = Article::with('user')
    ->limit(1000)
    ->get();
Enter fullscreen mode Exit fullscreen mode

Query Builder

$articles = DB::table('articles')
    ->join('users', 'articles.user_id', '=', 'users.id')
    ->limit(1000)
    ->all();

$articles = Article::hydrate($articles); 
Enter fullscreen mode Exit fullscreen mode

SQL

$articles = Article::fromQuery("select * FROM articles JOIN users ON articles.user_id = users.id limit 1000");
Enter fullscreen mode Exit fullscreen mode

Cheers!

Collapse
hesamzakerirad profile image
Hesam Rad Author

You're right... After all using ORM is much more cleaner and maintainable but I had this question in mind for a long time and I wanted to answer it myself and share the results.
BTW, I didn't know about hydrate. What a neat idea!
Cheers buddy.