sql - 根据与其他表的关系仅显示用户特定用户
问题描述
我正在尝试列出已注册某个主题的用户。所以我有这些表:
用户:
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
,但它不起作用。
解决方案
主题模型:
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();
推荐阅读
- python - 使用 Arduino ESP82266 从 Heroku Python App 获取数据
- javascript - 在django中将js连接到html不起作用
- javascript - Vuejs如何通过与变量中的点连接的键访问嵌套对象?
- java - 如何使用 joda 日期时间将字符串日期转换为 UTC 格式
- c# - 使用 Windows 窗体移植旧的 Flash 游戏 - 如何嵌入 Flash Player dll?
- python - 在列上合并 Pandas 数据框,并按同一列排序结果
- android - 如何在 Android 的 RecyclerView 上添加 onClickListener?
- android - 如何让我的 Android 应用程序连接到后端通道以接收更新并触发设备中的事件?
- python - python中的字符动画不起作用
- python-3.x - 如何使用 AppiumService() 从我的 python 代码启动 appium 服务器?