【问题标题】:Laravel 5 model class not found - hasMany未找到 Laravel 5 模型类 - hasMany
【发布时间】:2016-10-11 00:59:27
【问题描述】:

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

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

【问题讨论】:

  • 你为什么不直接从控制器public function index() { $companies = Company::get(); return view('frontpage', compact('companies')); }传递companies

标签: php mysql laravel laravel-5 eloquent


【解决方案1】:

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

替换

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

与任一

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-13
    • 2015-04-15
    • 2016-04-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-26
    • 2015-07-07
    相关资源
    最近更新 更多