我正在尝试列出已注册主题的用户。所以我有这些表:
用户:
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
之类的方法,但是没有用。
答案 0 :(得分:0)
在您的主题模型中,编写关系如下:
public function users()
{
return $this->belongsToMany(User::class);
}
或
public function users()
{
return $this->belongsToMany(User::class,'subject_user','user_id','id');
}
然后您可以在控制器中获得类似的主题:
$subjects = Subject::latest()->with('users')->get();
要查看结果,请使用return $subjects;
对于视图中的单个主题,请使用:
@foreach($subject->users() as $user)
{{$user->name}}
@endforeach
答案 1 :(得分:0)
主题模型:
public function users(){
return $this->belongsToMany('App\User');
}
用户模型:
public function subjects() {
return $this->belongsToMany('App\Subject');
}
在您的控制器中,您可以使用has这样的方法:
$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();
答案 2 :(得分:0)
所以我想我做到了。我将模型更改为:
public function users(){
return $this->belongsToMany('App\User');
}
然后在视图中:
@foreach ($subject->users()->where('subject_id', $subject->id)->get() as $user)
<h1>{{$user->name}}</h1>
@endforeach