Laravel 5从多个(3)表中获取数据

时间:2016-07-11 12:54:14

标签: laravel-5

我有3个表:员工,雇员配置文件,员工技能。模型关系如下

1. Employee Model

    public function employeeprofile(){
    return $this->hasOne('App\Employeeprofile', 'employee_id');
    }

    public function employeeskill(){
    return $this->hasMany('App\Employeeskill', 'employee_id);
    }

2. Employeeprofile Model

    public function employee(){
    return $this->belongsTo('App\Employee', 'employee_id');
    }

3. Employeeskill Model

    public function employee(){
    return $this->belongsTo('App\Employee', 'employee_id');
    }

员工表有列id,fName,lName,email。员工配置文件表具有id,employee_id,它是引用employee表,join_date等的外键。 Employeeskills表具有列id,employee_id,它是引用employee表和skill_name的外键。一名员工可以拥有许多技能。现在,我希望在控制器中访问employee表中的所有员工及其配置文件(employeeseprofile表)和他们的技能(employeeskills表),并将变量传递给视图并使用foreach显示每个员工。当我使用两个表(employee和employeeprofile)时,它工作正常,但在引入第三个表时,我没有得到结果。

我需要像

这样的东西
$employees = Employee::with('employeeprofile')->employee()->get();

然后我将$ employee varible传递给视图并执行

@foreach($employee as $employee)
Name: $employee->fName,
Joined: $employee->join_date,
Skill 1 : I list all the skills the employee has
@endforeach

我该如何解决?

1 个答案:

答案 0 :(得分:0)

您应该使用Eloquent ORM为您提供的优势。

您在Employee模型中定义的方法(例如employeeskill)可用于在用作属性/属性时获取所有相关对象。

$employees = Employee::all(); //get all (not soft-deleted) employees
foreach($employees as $e)
{
    $name = $e->fName; //The name of the employee
    $join = $e->join_date; //The join date
        foreach($employees->employeeskill as $skill) //Iterate over all skills of an employee
        {
            echo $skill->name; //echo the name of each skill
        }
}

查看the docs了解更多信息。