未找到Laravel 5模型类 - hasMany

时间:2016-06-10 06:56:34

标签: php mysql laravel laravel-5 eloquent

我试图让公司员工在模型中使用多种方法。但我得到了这个错误。

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

1 个答案:

答案 0 :(得分:8)

关系定义要求传递完全限定的类名。

替换

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

使用

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

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