Laravel - 使用联结表显示与当前用户相关的信息

时间:2018-04-25 19:47:09

标签: laravel eloquent

在我的数据库中,我有三个表,如:

用户

+----+---------------+-----------+
| id | name          | role      |
+----+---------------+-----------+
|  3 | Pavel Chekov  | student   |
|  5 | Nyota Uhura   | student   |
|  6 | Leonard McCoy | professor |
+----+---------------+-----------+

受试者

+----+--------------------------+
| id | name                     |
+----+--------------------------+
|  1 | Relational Databases     |
|  3 | Accessibility            |
|  4 | Software Engineering     |
|  5 | Marketing and Business   |
+----+--------------------------+

P.S。:每个主题都有对表的描述,此处未显示。

users_subjects

+----+---------+------------+
| id | user_id | subject_id |
+----+---------+------------+
|  1 |       6 |          1 |
|  2 |       6 |          3 |
|  3 |       3 |          1 |
|  4 |       3 |          3 |
|  5 |       3 |          5 |
+----+---------+------------+

然后我必须在我的模板中显示与当前登录用户(学生或教授)相关的主题,如下所示:

<section class="section">

    <div class="tile is-ancestor">

      @foreach ($subjects as $subject)

      <div class="tile is-parent">
        <article class="tile is-child box">
          <p class="title">{{ $subject->name }}</p>
          <div class="content">
            <p>{{ $subject->description }}</p>
          </div>
        </article>
      </div>

      @endforeach          

    </div>

</section>

将为用户关联的每个主题创建一个新的图块,填写该部分。我想只显示与当前用户相关的主题。

我怎样才能实现这一目标?提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

如果您在模型中正确定义了关系:

ImpersonationLevel = Impersonation

您应该能够简单地检索用户主题。

/**
 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
 */
public function subjects(){
    return $this->belongsToMany(User::class);
}

参考:https://laravel.com/docs/5.6/eloquent-relationships#many-to-many