繁体   English   中英

无法使用Laravel从两个不同的表中获取我想要的数据

[英]cant get the data I want from two different tables using Laravel

我有一个表,名为教师或 班级user_id,class_id ,我还有另一个表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();

这再次返回了相同的记录,但是对于每条记录,class属性当然为null,这在某些时候看起来是正确的,但是我的观点是,如果在类表中“ active”字段不对应,则不显示该记录就像with()中的where()stm是可选的。

我有点卡在这里...感谢您的帮助,意见!

您可以使用::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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM