Home > OS >  What is the real query behind Laravel's Model::belongsTo() method?
What is the real query behind Laravel's Model::belongsTo() method?

Time:01-06

For example, let's take a look to this model in a laravel project:

<?php
//...

class Post extends Model
{
   //...

   public function user()
   {
      return $this->belongsTo(User::class); // User model is previously defined
   }
}

Now I can get the user (author) info of a specific post:

Post::find(1)->user()->username;

Of course laravel has to run some DB queries to get the data; and I wanna know what is the query behind this belongsTo() method.

CodePudding user response:

You cant use the toSql() method to check query will run on laravel illuminate,

$sql = Person::query()->with('user')->find(1)->toSql();
dd($sql);

CodePudding user response:

try use this

$result=Post::with('user')->find(1);
dd($result);

and look the response belongs to is meaning to relation between tables if the relation is one to one use belongsTo and hasOne

if the relation is one to many use belongsTo and hasMany

  •  Tags:  
  • Related