首页 > 解决方案 > 根据与其他表的关系仅显示用户特定用户

问题描述

我正在尝试列出已注册某个主题的用户。所以我有这些表:

用户:

Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->boolean('admin')->default(false);
            $table->unsignedInteger('year');
            $table->unsignedBigInteger('department_id');
            $table->rememberToken();
            $table->timestamps();

            //$table->foreign('department_id')->references('id')->on('departments');
        });

主题:

Schema::create('subjects', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->timestamps();
            $table->string('name');
            $table->string('text');
            $table->unsignedInteger('year');
        });

这张表应该在这两者之间建立关系:

Schema::create('subject_user', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->timestamps();
            $table->unsignedBigInteger('subject_id');
            $table->unsignedBigInteger('user_id');

            $table->foreign('subject_id')->references('id')->on('subjects')->onDelete('cascade');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

        });

楷模:

主题:

public function users(){
        return $this->hasMany('App\User');
    }

用户:

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

现在,如果我单击带有某个 id 的某个主题,它应该将我重定向到列出该主题中的用户的页面。但我似乎无法让它发挥作用。我尝试了类似的东西@foreach($subject->users()->get() as $user) {{$user->name}} @endforeach,但它不起作用。

标签: sqllaravel

解决方案


主题模型:

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

用户模型:

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

在您的控制器中,您可以使用以下方法:

$users = User::has('subjects')->get();

如果您想在 WhereHas 方法中执行一些自定义过滤器传递作为闭包,例如:

$users = User::whereHas('subjects', function($q){
    $q->where('created_at', '>=', '2019-09-12');
})->get();

如果您想获得订阅特定主题的用户,您应该将过滤器传递给 whereHas,就像我上面描述的那样:

$users = User::whereHas('subjects', function($q) use ($subject_id){
    $q->where('subjects.id', $subject_id);
})->get();

推荐阅读