我如何从3张桌子中获得价值?

时间:2018-11-07 07:52:53

标签: mysql laravel-5

表:项目 enter image description here

表:projects_departments enter image description here 表格:部门enter image description here

这是模型项目

public function projects_departments() {
    return $this->hasMany(Project_department::class); 
}

这是Model Project_department

public function projects()
{
    return $this->belongsTo(Project::class);
}

public function departments()
{
    return $this->belongsTo(Department::class);
}

这是模特部

public function projects()
{
    return $this->hasMany(Project::class);
}

public function projects_departments() {
    return $this->hasMany(Project_department::class); 
}

这是我的刀刃

project->departments->department_name

这是我的错误 SQLSTATE [42S22]:找不到列:1054“ where子句”中的未知列“ projects_departments.project_id”(SQL:从projects_departments中选择*,其中projects_departmentsproject_id = 48,{{ 1}}。projects_departments不为空)

1 个答案:

答案 0 :(得分:2)

$project = DB::table('projects')
        ->select(*)
        ->join('Department', 'projects_departments.department_id', '=', 'Department.id')
        ->join('projects_departments', 'projects_departments.project_id', '=', 'projects.id')

        ->get();

让我们尝试一下