0
votes

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 | [email protected] | NULL              | admin    | NULL           | NULL       | NULL       |
|  2 | user1 | [email protected] | NULL              | user1    | NULL           | NULL       | NULL       |
|  3 | user2 | [email protected] | 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?

1

1 Answers

2
votes

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();