我如何通过Laravel关系进行两次联接?

时间:2017-12-10 09:38:51

标签: php mysql sql laravel

这是我的表结构:

// roles
+----+-------+
| id | name  |
+----+-------+
| 1  | admin |
| 2  | stuff |
+----+-------+

//pages
+----+---------------------+
| id |         path        |
+----+---------------------+
| 1  | users/list          |
| 2  | users/list/paginate |
| 3  | users/make          |
| 4  | posts/add           |
| 5  | posts/edit          |
+----+---------------------+

page_role
+---------+----------+
| page_id | role_id  |
+---------+----------+
| 1       | 1        |
| 1       | 2        |
| 1       | 3        |
| 1       | 4        |
| 1       | 5        |
| 2       | 4        |
| 2       | 5        |
+---------+----------+

我尝试做的就是获取每个角色的所有页面。如何通过在Laravel中使用关系来做到这一点?

以下是纯SQL的当前解决方法:

SELECT p.* FROM roles r
INNER JOIN page_role  pr on r.id = pr.role_id
INNER JOIN pages      p  on p.id = pr.page_id
ORDER BY p.id DESC

1 个答案:

答案 0 :(得分:0)

首先在Role模型中定义belongsToMany()关系:

public function pages()
{
    return $this->belongsToMany(Page::class);
}

然后,要获取每个角色的所有页面,请使用with()方法:

$rolesWithPages = Role::with('pages')->get();

然后,您将能够遍历每个角色的角色和页面:

@foreach ($rolesWithPages as $role)
    Role: {{ $role->name }}<br>
    @foreach ($role->pages as $page)
        Page: {{ $page->title }}<br>
    @endforeach
@endforeach