PHP Lumen在null上调用成员函数connection()

bi4*_*chi 23 php laravel eloquent lumen

调用null上的成员函数connection()是我在尝试在流明中使用Eloquent模型时收到的错误.

控制器功能:

/**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {

        $employees = Employee::orderBy('first_name', 'asc')->get();
dd($employees);

        $response['precontent'] = view('admin::employee.search')->render();

        $response['content'] = view('admin::employee.index')
            ->with(['employees' => $employees])
            ->render();

        $response['title'] = 'Employees';

        return $response; 

    }
Run Code Online (Sandbox Code Playgroud)

模型:

    <?php
    namespace App;

use Illuminate\Database\Eloquent\Model;

class Employee extends Model 
{

    protected $table = 'system_core.employees';

    protected $fillable = [
        'user_id',
        'first_name',
        'last_name',
        'position',
        'primary_address',
        'secondary_address',
        'phone_1',
        'phone_2',
        'birth_date',
        'start_date',
        'end_date'
    ];

}
Run Code Online (Sandbox Code Playgroud)

我对Laravel非常有经验,但刚开始我的第一个Lumen项目仅用于API,我不确定为什么会抛出这个错误.也许只是我的连接设置?所有查询都必须按以下方式运行吗?:

$results = app('db')->select("SELECT * FROM users");
Run Code Online (Sandbox Code Playgroud)

谢谢!

the*_*len 91

您应该$app->withEloquent()像这样启用Eloquent bootstrap/app.php.

https://lumen.laravel.com/docs/5.2/database#basic-usage

  • 您还必须取消注释上一行(`$ app-&gt; withFacades();`,因为Eloquent确实使用Facades)。 (2认同)

Val*_*Shi 18

根据 2021 年,这里是用于检查以修复此错误的检查表。

你必须:

  1. 通过例如 PHPMyAdmin 手动创建数据库;
  2. .env文件中配置它的数据库连接(即 set DB_CONNECTION, DB_DATABASE, DB_USERNAME, DB_PASSWORD);
  3. 按照上面的答案取消注释 $app->withFacades();$app->withEloquent();输入bootstrap/app.php;
  4. 如果您在 PHPUnit 测试中使用 Eloquent 模型,您必须首先通过将以下行添加到您的测试类方法启动 Lumen(或 Laravel): setUp()
    parent::setUp()
    
    Run Code Online (Sandbox Code Playgroud)

那应该解决它。


小智 9

bootstrap/app.php

然后取消注释

$app->withEloquent();
Run Code Online (Sandbox Code Playgroud)