我有非常基本的问题。在 L4 中,下面的方法开箱即用,所以现在我迷路了。请帮忙。几天前,我开始了一个Laravel 5.0项目。我现在有全新的、干净的安装。
问题1:当我尝试从数据库中获取任何内容时
$headquote = DB::table('quotation_texts')->find(176);
我明白这个:
Class 'App'Http'Controllers'DB' not found
问题 2:在克隆用户.php模型之前,将类名更改为"报价"。以下是文件报价的内容.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
任何想法如何解决问题?
这里的问题是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 手册中的命名空间
又快又脏又脏
use DB;
或
'DB::table...
只需添加控制器的顶部即可。
use DB;
尝试如下:
<?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);
}
}
}
?>
在标头的 db 之前使用反斜杠,然后通常可以像以前编写的那样使用它。
下面是示例:
Use 'DB;
然后在控制器类中,您可以像以前一样使用,例如:
$item = DB::table('items')->get();
名称间距存在问题,如 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';
}
我喜欢做这个我认为更干净的女巫:
1 - 将模型添加到命名空间:
use App'Employee;
2 - 然后你可以做:
$employees = Employee::get();
或者可能是这样的:
$employee = Employee::where('name', 'John')->first();