如何在配置文件中进行数据库查询? [英] How to make database query inside a config file?

查看:232
本文介绍了如何在配置文件中进行数据库查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力弄清楚如何在Laravel配置文件中进行数据库查询.

I am struggling to figure out how I can make a database query inside of a Laravel config file.

我当前正在使用:

<?php
// config/database.php

$results = \Illuminate\Support\Facades\DB::select( \Illuminate\Support\Facades\DB::raw("select version()") );
$mysql_version =  $results[0]->{'version()'};
dd($mysql_version);

return [

...

但是我收到的错误是:

RuntimeException in Facade.php line 218:
A facade root has not been set.
in Facade.php line 218
at Facade::__callStatic('raw', array('select version()')) in database.php line 2
at require('/Users/test/code/clooud/config/database.php') in LoadConfiguration.php line 70
at LoadConfiguration->loadConfigurationFiles(object(Application), object(Repository)) in LoadConfiguration.php line 39
at LoadConfiguration->bootstrap(object(Application)) in Application.php line 208
at Application->bootstrapWith(array('Illuminate\\Foundation\\Bootstrap\\LoadEnvironmentVariables', 'Illuminate\\Foundation\\Bootstrap\\LoadConfiguration', 'Illuminate\\Foundation\\Bootstrap\\HandleExceptions', 'Illuminate\\Foundation\\Bootstrap\\RegisterFacades', 'Illuminate\\Foundation\\Bootstrap\\RegisterProviders', 'Illuminate\\Foundation\\Bootstrap\\BootProviders')) in Kernel.php line 160
at Kernel->bootstrap() in Kernel.php line 144
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 116
at Kernel->handle(object(Request)) in index.php line 57
at require('/Users/test/code/clooud/public/index.php') in server.php line 128

如何确保此查询产生输出并解决此错误?

How can I make sure that this query results in an output and resolve this error?

感谢您的帮助!

推荐答案

config/database.php文件中保留默认值或空值.创建新的服务提供商(使用artisan命令或手动创建)

Leave a default or null value in your config/database.php file. Create a new service provider (either with the artisan command or manually)

php artisan make:provider DatabaseConfigProvider

然后将新的提供程序添加到config/app.php文件中的$providers数组中.

Then add the new provider to the $providers array in your config/app.php file.

最后将以下代码添加到boot()方法.

Finally add the following code to the boot() method.

public function boot()
{
    $result= \DB::select('select version() as version')[0];
    $this->app['config']->put('database.connections.mysql.version', $result->version);
}

put()参数中的键可以是您想要的任何值.

The key in the put() argument can be whatever you want.

这篇关于如何在配置文件中进行数据库查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆