Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

p0t4t0's avatar

When creating relations with the Laravel ORM, what is the raw MySQL query behind it?

For example, if I have a Posts and a Comments model and "bind" (not sure if it's the proper term) comments to a post with...

class Post {

    public function comments()
    {
        return $this->hasMany('App\Comment');
    }

}

What is the raw MySQL query behind that? I'm kind of weak on MySQL so I just want to know to learn more about it and how should I structure my future database queries with the Laravel ORM.

0 likes
4 replies
jlrdw's avatar

Jeffrey has a video that explains this, but basically two SQL queries.

tykus's avatar

There is no query until the relation is used - this might be a read, write, or delete. An example of a read would be if you eager-load comments relation when getting posts then Laravel will make a query to get the post(s), then make a second query to fetch the comments associated with the post id(s) returned from the first query, e.g.

// Eloquent query
$posts = Post::with('comments')->get();

// SQL resulting from eager-loading
select * from posts;
select * from comments where post_id in (1,2,3,4....); // post ids found in the first query

Laravel then makes available a property on each Post instance which is named after the relation, i.e. comments which will be a Collection (because it is a HasMany relation) of the comments with the post_id matching that Post instance.

BezhanSalleh's avatar
Level 25

@p0t4t0 there are so many ways:

//1
DB::enableQueryLog();
$queries = DB::getQueryLog();
dd($queries );

//2. you listen to it, by adding the following inside your boot method in //AppServiceProvider
        DB::listen(function ($query) {
            // $query->sql
            // $query->bindings
            // $query->time
        });
//3. for a single query
//in your case get the comments of a single post
    $post = Post::first();
    $comments = $post->comments()->get();
    $rawQuery = $comment->toSql();

//4. finally the best way is to install this package https://github.com/barryvdh/laravel-debugbar

//just require through composer
composer require barryvdh/laravel-debugbar

and then in .env file set the APP_DEBUG=true... you are done.

It has many more features, enabling/disabling at runtime, and bridge collectors... you can refer to the link for more options. cheers~

Snapey's avatar

Eloquent relationships don't use joins so basically if you had

   $post=Post::with('comments')->find(5);

//Gives

Select * from posts where id =5

Select * from comments where post_id=5

Best thing is to install laravel debugbar then you can see what queries are used in each view

Please or to participate in this conversation.