如何使用Laravel框架执行MySQL查询?

时间:2022-09-20 14:59:45

So I recently looked into the Laravel framework as I've been wanting to do for several months and so far It looks great and has some really helpful stuff in it.

所以我最近调查了Laravel框架,因为我一直想做几个月,到目前为止它看起来很棒并且有一些非常有用的东西。

However I've been trying to actually use database queries so that I can make use of real data but when I've tried to I haven't had much success.

然而,我一直在尝试实际使用数据库查询,以便我可以利用真实数据,但是当我尝试时,我没有取得多大成功。

I've configured the \config\database.php MySQL section, then tried using DB:: and all I got was an error:

我已经配置了\ config \ database.php MySQL部分,然后尝试使用DB ::我得到的只是一个错误:

the DB class in controllers doesn't exist

控制器中的DB类不存在

I have been reading through all the documentation and found nothing

我一直在阅读所有文档,一无所获

<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use DB;

class SongsController extends Controller {

        public function getSongs(){
        $songs = DB::table('songs')->get();

                return $songs;

        }      

}

View:

<?php  
        foreach ($songs as $song){
    var_dump($song->song);
        }

My mysql in \config\database.php:

我在\ config \ database.php中的mysql:

'mysql' => [
    'driver'    => 'mysql',
    'host'      => env('DB_HOST', 'localhost'),
    'database'  => env('DB_DATABASE', 'songs'),
    'username'  => env('DB_USERNAME', 'root'),
    'password'  => env('DB_PASSWORD', 'password'),
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
    'strict'    => false,
],

2 个解决方案

#1


In your mysql config:

在你的mysql配置中:

'database'  => env('DB_DATABASE', 'songs'),

It says: look if enviroment variable is set, if it exists in your .env file (in your root), use it, if not, use default "songs".

它说:看看是否设置了环境变量,如果它存在于你的.env文件中(在你的根目录中),使用它,如果没有,则使用默认的“歌曲”。

http://laravel.com/docs/5.0/configuration#environment-configuration

#2


You need to add use DB; in the top of your file. Remember Laravel5 uses namespaces.

你需要添加使用DB;在文件的顶部。记住Laravel5使用名称空间。

<?php namespace App\Http\Controllers;
use DB;

#1


In your mysql config:

在你的mysql配置中:

'database'  => env('DB_DATABASE', 'songs'),

It says: look if enviroment variable is set, if it exists in your .env file (in your root), use it, if not, use default "songs".

它说:看看是否设置了环境变量,如果它存在于你的.env文件中(在你的根目录中),使用它,如果没有,则使用默认的“歌曲”。

http://laravel.com/docs/5.0/configuration#environment-configuration

#2


You need to add use DB; in the top of your file. Remember Laravel5 uses namespaces.

你需要添加使用DB;在文件的顶部。记住Laravel5使用名称空间。

<?php namespace App\Http\Controllers;
use DB;