我仍在努力思考 whereHas()
方法。我的情况是这样的。我想拉所有属于类的用户
这是关系
类模型
public function users() {
return $this->belongsToMany('App\User')->withTimestamps();
}
用户模型
public function classes() {
return $this->belongsToMany('App\Classes')->withTimestamps();
}
Controller
$class_us = User::whereHas('classes', function ($query) {
$query->where('class',1);
})->get();
当我执行 dd($class_us)
时,我得到一个空集合。
我该如何解决这个问题?
谢谢。
最佳答案
在 whereHas clouse 中,构建器实例来自相关模型,
$class_us = User::whereHas('classes', function ($query) {
// here the builder belongs to Class model not User model
$query->where('id',1); // id because classes table has column as id
})->get();
关于php - laravel 从数据库中拉取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40929875/