我有一个名为instructor_class: user_id, class_id的表,我有另一个表classes: id,时间,活动。
我想显示单个用户的类,但只显示那些活动为0或1的类。
我当前的代码是这样的:
return InstructorClass::with('classes.session')->where('user_id', '=', $userId)->get();
这段代码显示了我所有的东西,然后我尝试了下面的代码:
$active = 1;
return InstructorClass::with(['classes' => function ($q) use ($active) {
$q->where('active', '=', $active); // '=' is optional
}])
->where('user_id', '=', $userId)
->get();
这再次返回我相同的记录,但当然类属性为每条记录为空,这在某些时候看起来是正确的,但我的观点是,如果"活动"字段不对应于类表不显示记录,似乎where() stm with()是可选的..
我有点困在这里…非常感谢您的帮助、意见!
您可以使用::has('classes')
只返回具有相关类的模型
return InstructorClass::has('classes')->with(['classes' => function ($q) use ($active) {
$q->where('active', $active);
}])
->where('user_id', '=', $userId)
->get();
没想到会这么简单:
return InstructorClass::with('classes.session')
->join('classes', 'classes.id', '=', 'instructor_class.class_id')
->where('classes.active', '=', 1)
->where('user_id', '=', $userId)
->get();