【问题标题】:PHP Lumen Call to a member function connection() on nullPHP Lumen 在 null 上调用成员函数 connection()
【发布时间】:2016-09-17 22:31:08
【问题描述】:

我在尝试在 Lumen 中使用 Eloquent 模型时收到此错误。

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

控制器功能:

/**
     * 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; 

    }

型号:

    <?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'
    ];

}

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

$results = app('db')->select("SELECT * FROM users");

谢谢!

【问题讨论】:

    标签: php laravel eloquent lumen


    【解决方案1】:

    您应该取消注释 bootstrap/app.php 中的 Eloquent $app-&gt;withEloquent() 调用。

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

    更新:

    最新版本的文档https://lumen.laravel.com/docs/5.8/database,查看Eloquent ORM

    部分

    【讨论】:

    • 您还必须取消注释上一行($app-&gt;withFacades();,因为 Eloquent 确实使用 Facades)。
    【解决方案2】:

    根据 2021 年,这里是检查以修复此错误的检查清单。

    你必须:

    1. 通过例如手动创建数据库PHPMyAdmin;
    2. Configure数据库连接它在.env文件中(即设置DB_CONNECTIONDB_DATABASEDB_USERNAMEDB_PASSWORD);
    3. 根据上面的答案uncomment$app-&gt;withFacades();$app-&gt;withEloquent();bootstrap/app.php中的行;
    4. 如果你在 PHPUnit 测试中使用 Eloquent 模型,你必须先在 boot the Lumen(或 Laravel)添加以下行到你的测试类 setUp()method
      parent::setUp()
      

    这应该可以解决它。

    【讨论】:

      【解决方案3】:

      我想你只是取消注释 $app-&gt;withFacades();, $app-&gt;withEloquent(); bootstrap/app.php; 中的行

      再检查一次,它对我有用。

      【讨论】:

        【解决方案4】:

        这个错误的另一个不太常见的原因是你试图在它准备好之前访问一个 eloquent 模型,例如在 Job 的构造函数中或者可能在 app/Console/Kernel.php

        如果是这种情况,请尝试这样做

        use Illuminate\Support\Facades\DB;
        
        $model =  DB::table('table_name')
                    ->where('field_name', 'field_value')->first()
        

        【讨论】:

        • 这是我所面临的谢谢(y)
        【解决方案5】:

        转到bootstrap/app.php

        然后取消注释

        $app->withEloquent();
        

        【讨论】:

          猜你喜欢
          • 2018-02-06
          • 2018-08-08
          • 2019-01-12
          • 2021-01-25
          • 1970-01-01
          • 2019-02-24
          • 2021-01-26
          • 1970-01-01
          相关资源
          最近更新 更多