简体   繁体   中英

Laravel php script DB class not found

I'm trying to write a script for laravel that queries my database and fetches tables, but I'm not sure what to include in the file in order to get the DB class to work.

Thus far my code looks like:

$tables = DB::query("SHOW TABLES"); foreach ($tables as $table) { print $table . "\\n"; }

I've tried using require "../../vendor/autoload.php" but that doesn't help.

So for instance, the DB class works fine if I call it within a controller, but not if I create a directory, say /application/scripts and create a file test.php . If I try to call DB in that file, the DB class isn't defined (for good reason). I'm wondering what I need to require in that file in order for that class to be defined.

I would suggest using the Illuminate/Database package (part of Laravel 4). You won't get the DB interface, because that's a special facade provided by the Laravel Framework, but all the query builder functionality is available through the capsule.

Install illuminate/database using composer and then follow the included readme notes (included below for completeness).


Illuminate Database

Usage Outside Of Laravel 4

$config = array(
    'fetch' => PDO::FETCH_CLASS,
    'default' => 'mysql',
    'connections' => array(
        'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'laravel',
            'username'  => 'root',
            'password'  => 'password',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),
    ),
);

$capsule = new Illuminate\Database\Capsule($config);

// If you want to use the Eloquent ORM...
$capsule->bootEloquent();

// Making A Query Builder Call...
$capsule->connection()->table('users')->where('id', 1)->first();

// Making A Schema Builder Call...
$capsule->connection()->schema()->create('users', function($t)
{
    $t->increments('id');
    $t->string('email');
    $t->timestamps();
});

You do not need to include anything. Laravel will include what it needs and setup the system itself. You are using a variable called $db but it is not defined and means/does nothing. What you are looking for is the DB class. Try this:

$tables = DB::query('SHOW TABLES');
foreach ($tables as $table)
{
    echo $table.PHP_EOL;
}

Also, check out the Fluent DB class documentation: http://laravel.com/docs/database/fluent

...Isn't it DB::query() ? A call to the database engine is through a class, not a variable, for scoping issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM