Laravel 查询生成器左联接

Laravel Query Builder left join

有人可以告诉我,为什么我无法使用左连接从 table 节中 select 节。我想要 table 中的教师列表,我能够访问来自教师 table 的所有数据,但我无法使用左连接查看部分。 教师 Table 有 section_id 列,该列应该访问第 table 部分列中的数据。

现在,当我尝试使用 {{$teacher->section}} 获取视图中的数据时出现错误 下面是我的代码。

public function listteachers(Request $request)
{
  $teachers = DB::table('teachers')
  ->select('teachers.*')
  ->leftjoin('sections', 'teachers.section_id', '=', 'sections.id')
  ->orderBy('pass_exp', 'ASC')
  ->get();
return view('teachers.list',compact('teachers'));
}

您需要从查询的 table 部分中 select 您想要的列。

例如:

$teachers = DB::table('teachers')
    ->select('teachers.*', DB::raw('sections.name as section_name'))
    ->leftJoin('sections', 'teachers.section_id', '=', 'sections.id')
    ->orderBy('pass_exp', 'ASC')
    ->get();

将代码改成下面的

  $teachers = DB::table('teachers')
        ->select('teachers.*','sections.name as section_name')
        ->leftJoin('sections', 'teachers.section_id', '=', 'sections.id')
        ->orderBy('pass_exp', 'ASC')
       ->get();