我正在开发laravel 5应用程序。 我有问题从两个数据库表获取结果。这就是我所拥有的:
table A: 'courses'
id | Course
————————————————
1 | Math
2 | History
3 | Geography
4 | Computer
和表B
user_id | classroom_id | course
1 | 5 | 3
1 | 5 | 4
1 | 6 | 2
我为每个循环返回了表A,但是我想检查user_id 1必须在for-each循环的每一列上返回true或false的哪些课程。 像这样:
user_id 1的返回项目:
id | course | status
____________________________
1 | Math | false
2 | History | true
3 | Geography | true
4 | Computer | true
这是我:
$AllList = DB::table('users')
->join('courses', 'users.id', '=', 'courses.parent_id')
->join('classroom', 'users.id', '=', 'classroom.user_id')->where('classroom_id', '=', 5)
->get();
感谢任何帮助。
答案 0 :(得分:2)
只需将join
替换为leftJoin
:
$AllList = DB::table('courses')
->select('courses.id','course.name')
->leftJoin('users', 'users.id', '=', 'courses.parent_id')
->join('classroom', 'users.id', '=', 'classroom.user_id')->where('classroom_id', '=', 5)
->get();
Course
字段将为NULL
,因此如果没有匹配则为空字符串
答案 1 :(得分:1)
以下代码行将帮助您......
$getCourse = DB::table('courses')->get(['id','course']);
$getCourse = collect($getCourse)->map(function($x){ return (array) $x; })->toArray();
foreach ($getCourse as $key => $value)
{
$flag = DB::table('classroom')
->where('user_id',1)
->where('course',$value['id'])
->pluck('id');
if($flag)
{
$getCourse[$key]['status'] = true;
}
else
{
$getCourse[$key]['status'] = false;
}
}
dd($getCourse);