57

我有一个非常基本的问题。在 L4 中,以下方法是开箱即用的,所以现在我迷路了。请帮忙。几天前我开始了一个 Laravel 5.0 项目。我现在有全新、干净的安装。

问题 1:当我尝试从数据库中获取任何内容时

$headquote = DB::table('quotation_texts')->find(176);

我明白了:

Class 'App\Http\Controllers\DB' not found

问题 2:在我克隆 User.php 模型之前,将类名更改为“引用”。以下是放在 App 根文件夹中的 Quotations.php 文件的内容:

<?php namespace App;

 use Illuminate\Database\Eloquent\Model;

 class Quotation extends Model  {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'quotation_texts';
}

任何使用模型的尝试

$headquote = Quotation::find(176);

以这个结束:

Class 'App\Http\Controllers\Quotation' not found

有什么想法可以解决这个问题吗?

4

7 回答 7

143

这里的问题是 PHP 命名空间。你需要学习如何使用它们。由于您的控制器在App\Http\Controllers命名空间中,如果您引用任何其他类,则需要use在文件开头添加前导反斜杠(或适当的命名空间)或添加语句(在类定义之前)。

因此,在您的情况下,您可以使用:

$headquote = \DB::table('quotation_texts')->find(176);
$headquote = \App\Quotation::find(176);

或添加您的控制器类use语句,以便您的控制器类的开头可能如下所示:

<?php

namespace App\Http\Controllers;

use DB;
use App\Quotation;

有关命名空间的更多信息,您可以查看如何使用其他命名空间中的对象以及如何在 PHP 中导入命名空间PHP 手册中的命名空间

于 2014-11-17T07:19:20.987 回答
15

又快又脏

use DB; 

或者

\DB::table...
于 2016-05-16T23:43:11.497 回答
7

只需添加控制器的顶部即可。

use DB;
于 2016-08-01T12:38:52.673 回答
1

在标头上的 db 之前使用反斜杠,然后通常可以像之前编写的那样使用它。

这是示例:

Use \DB;

然后在您的控制器类中,您可以像以前一样使用,例如:

$item = DB::table('items')->get();
于 2017-06-11T15:47:06.210 回答
1

试试这样:

<?php

    namespace App\Http\Controllers;

    use Illuminate\Http\Request;

    use DB;

    class UserController extends Controller
    {

    function  index(){

    $users = DB::table('users')->get();

    foreach ($users as $user)
    {
        var_dump($user->name);
    }

    }
  }

?>
于 2017-06-20T16:28:49.563 回答
0

laravel 5.2.3 中的名称间距存在问题

use DB;
use App\ApiModel; OR  use App\name of model; 

DB::table('tbl_users')->insert($users); 

OR

DB::table('table name')->insert($users);



model 

class ApiModel extends Model
    {

        protected $table='tbl_users';

}
于 2016-09-22T05:27:17.570 回答
0

我喜欢做这个我认为更干净的女巫:

1 - 将模型添加到命名空间:

use App\Employee;

2 - 然后你可以这样做:

$employees = Employee::get();

或者可能是这样的:

$employee = Employee::where('name', 'John')->first();
于 2020-04-21T22:01:01.360 回答