2016-06-10 98 views
2

我想讓公司的員工使用模型中的很多方法。但是我得到這個錯誤。找不到Laravel 5模型類 - hasMany

Fatal error: Class 'Employee' not found (View: /home/vagrant/Code/laravel/resources/views/frontpage.blade.php) 

這裏是我的控制器:

namespace App\Http\Controllers; 
use Illuminate\Http\Request; 

use App\Http\Requests; 
use App\Company; 
use App\Employee; 

    public function index() 
    { 
     $data = Company::get(); 
     $data = array(
      'companies' => $data, 
     ); 


     return view('frontpage', $data); 
    } 

這裏是我的模型:第一種是Company.php

namespace App; 

use Illuminate\Database\Eloquent\Model; 
use App\Employee; 

class Company extends Model{ 

    protected $table = 'company'; 

    public function employee() 
    { 
     return $this->hasMany('Employee', 'company_id', 'id'); 
    } 
} 

下面是其他模型,Employee.php

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Employee extends Model{ 

    public $table = "employee"; 

} 

這裏是視圖

@extends('layouts.master') 

@section('content') 

<div> 
    @foreach ($companies as $company) 
     <p>This is company {{ $company->name }}</p> 
     <p>{{ print_r($company->employee) }}</p> 
    @endforeach 
</div> 

@stop 
+0

你爲什麼不通過'companies'直接像這樣從控制器 '公共功能指數() { $ companies = Company :: get(); return view('frontpage',compact('companies')); }'? – linuxartisan

回答

6

關係定義需要傳遞完全限定的類名。

更換

return $this->hasMany('Employee', 'company_id', 'id'); 

與任何

return $this->hasMany('App\Employee', 'company_id', 'id'); 

return $this->hasMany(Employee::class, 'company_id', 'id');