0

What does a sql query look like when using the belongsToMany method in laravel 6.0?

For example, we have three tables in the database:users, roles, role_user.

users
+----+-------+-----------------+-------------------+----------+----------------+------------+------------+
| id | name  | email           | email_verified_at | password | remember_token | created_at | updated_at |
+----+-------+-----------------+-------------------+----------+----------------+------------+------------+
|  1 | admin | admin@gmail.com | NULL              | admin    | NULL           | NULL       | NULL       |
|  2 | user1 | user1@gmail.com | NULL              | user1    | NULL           | NULL       | NULL       |
|  3 | user2 | user2@gmail.com | NULL              | user2    | NULL           | NULL       | NULL       |
+----+-------+-----------------+-------------------+----------+----------------+------------+------------+
roles
+----+---------+-------------+------------+------------+
| id | name    | description | created_at | updated_at |
+----+---------+-------------+------------+------------+
|  1 | admin   | NULL        | NULL       | NULL       |
|  2 | user    | NULL        | NULL       | NULL       |
|  3 | editor  | NULL        | NULL       | NULL       |
|  4 | manager | NULL        | NULL       | NULL       |
+----+---------+-------------+------------+------------+
role_user
+---------+---------+------------+------------+
| role_id | user_id | created_at | updated_at |
+---------+---------+------------+------------+
|       1 |       1 | NULL       | NULL       |
|       2 |       2 | NULL       | NULL       |
|       3 |       3 | NULL       | NULL       |
|       4 |       3 | NULL       | NULL       |
+---------+---------+------------+------------+

Im model User

public function roles()
    {
        return $this->belongsToMany('App\Role');
    }

What does a sql query look like when using the $this->belongsToMany('App\Role'); method in laravel 6.0?

Egene Brawn
  • 13
  • 1
  • 4

1 Answers1

3

Laravel can easily tell you that.

$user->roles()->toSql();

For a more comprehensive experience, you can log all queries instead. See this stackoverflow post for more.

DB::connection()->enableQueryLog();
$queries = DB::getQueryLog();
mrhn
  • 17,961
  • 4
  • 27
  • 46