【问题标题】:Using Illuminate DB outside of Laravel, can't use DB::table()在 Laravel 之外使用 Illuminate DB,不能使用 DB::table()
【发布时间】:2021-03-19 15:01:12
【问题描述】:

我已经安装了一些 Illuminate 包在 Laravel 之外使用。但是我不能使用任何 DB 方法。

例如:

$this->query = DB::table((new Vehicle())->getTable())->query();

上面给了我这个错误:

错误:RuntimeException:尚未设置外观根。在 /var/www/vendor/illuminate/support/Facades/Facade.php:218 堆栈跟踪:#0 /var/www/app/Services/PickCarouselService.php(37): Illuminate\Support\Facades\Facade::__callStatic () #1

在我的 Ide 中,我在 ::table 上收到以下消息:

在 \Illuminate\Support\Facades\DB 中找不到方法“表”

我可以使用模型和一切都很好,只是不能直接使用数据库,我该如何解决这个问题?

编辑 1

如何创建自己的 DB 外观实例?我们确实有以下内容,会不会类似?如果是这样,我会为Factory 传递什么到DatabaseManager

$app->instance(Database::class, (new Database($app))->boot()->getConnection());
$app->alias(Database::class, 'database');

编辑 2

不要认为我这样做是正确的,因为我不太确定我会为app 传递什么。

$app = new Application();

$app->instance(Database::class, new DatabaseManager(null, new ConnectionFactory($app)));
$app->alias(DatabaseManager::class, 'db');
// Application

<?php

namespace App;

use Illuminate\Container\Container;

class Application extends Container
{
    protected $basePath = '/var/www';

    public function __construct()
    {
        $this->bindPathsInContainer();
        $this->registerBaseBindings();
    }
...

【问题讨论】:

  • 你从composer require illuminate/database正确安装数据库了吗?
  • 我认为没有可用的应用程序容器就不能使用外观。 DB 门面创建了一个 DatabaseManager 的实例,因此您可以手动创建一个
  • 检查它的配置here
  • @apokryfos 我如何手动制作一个?查看更新的问题。
  • @Joseph 安装正确,配置正确。

标签: php eloquent


【解决方案1】:

设法弄清楚如何创建自定义外观。但是如果我可以像DB::table 一样使用它,那就太好了,但这很有效:


$app = new Application();

$app->singleton('db.factory', function ($app) {
    return new ConnectionFactory($app);
});

$app->singleton('db', function ($app) {
    return new DatabaseManager($app, $app['db.factory']);
});
$this->query = app()->db->table('tablename');

【讨论】:

  • 使用上面的$app 对象调用\Illuminate\Support\Facade::setFacadeApplication($app) 可能会起作用让外墙工作
猜你喜欢
  • 2015-03-13
  • 1970-01-01
  • 2014-07-12
  • 2015-07-14
  • 2016-11-26
  • 1970-01-01
  • 2016-12-31
  • 2015-04-13
  • 1970-01-01
相关资源
最近更新 更多