2016-07-11 9 views
0

私は3つのテーブルを持っています:employees、employeeprofiles、employeeskills。モデルの関係は次のとおりです。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という列があります。従業員プロファイルテーブルには、従業員テーブル、join_dateなどを参照する外部キーであるid、employee_idがあります。 Employeeskillsテーブルには、従業員テーブルとスキル名を参照する外部キーであるカラムid、employee_idがあります。 1人の社員が多くのスキルを持つことができます今私は、そのプロファイル(employeeprofileテーブル)とそのスキル(employeeskillsテーブル)を持つコントローラ内の従業員テーブルのすべての従業員にアクセスし、その変数をビューに渡してforeachを使用して各従業員を表示したいとします。私は2つのテーブル(従業員とemployeeprofile)を使用すると、それは正常に動作しますが、3番目のテーブルを導入すると、私は結果を得ることはありません。

私はその後、私はビューに$従業員varibleに合格し、どのように私はそれについて行かない

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

を行う

$employees = Employee::with('employeeprofile')->employee()->get(); 

ようなものが必要?

答えて

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をご覧ください。

関連する問題