我在使用laravel 5查询构建器进行Employee管理系统时遇到问题 . 这是我的EmployeesController
<?php
namespace App\Http\Controllers;
use App\Employee;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class EmployeesController extends Controller
{
public function index()
{
// $employees = Employee::all();
// return view('employees.index', compact('employees'));
$employees = DB::table('employees')->get();
return view('employees.index', compact('employees'));
}
}
当我使用注释掉的代码时,视图工作,我可以看到我的员工列表
$employees = Employee::all();
return view('employees.index', compact('employees'));
我在这里看到了answer,我按照建议做了但没有运气 . 我添加了使用DB;在命名空间声明之后还尝试了代码
$employees = \DB::table('employees')->get();
但是它会引发另一个错误,即在第6行的非对象上调用成员函数count() . 我甚至从C:\ xampp \ htdocs \ laravel5project \ vendor \ laravel \ framework \ src \复制了DB.php文件照亮\ Support \ Facades到App文件夹(C:\ xampp \ htdocs \ laravel5project \ app)但仍然没有运气 . 我也试图明确地给它命名空间
use Illuminate\Support\Facades\DB
这是观点
@extends('layouts.default')
@section('PageTitle', 'Employee List')
@section('content')
@if ( !$employees->count() )
There are no Employees!
@else
<table id="tblEmployee" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
@foreach( $employees as $employee )
<tr>
<td>{{$employee->Name}}</td>
</tr>
@endforeach
</tbody>
</table>
@endif
@endsection
可能是什么问题呢?
1 回答
DB
不在您当前的命名空间App\Http\Controllers
中 . 所以你可以在顶部导入它或者以反斜杠
\DB::table(...)
开头 . 这解决了类未找到的异常 .但是,您没有获得Laravel Employee模型集合,而是获得一组数据库行 . 数组不是具有count()函数的对象,这会导致最终错误 .
更新:Laravel 5.3将返回Collection对象而不是数组 . 所以count()会对此有所帮助 .