Im my routes.php我有以下内容:
<?php
Route::group(array(), function () {
View::share('roots', Category::roots()->get());
$tree = Category::get()->toHierarchy()->toArray();
View::share('categories', $tree);
Route::get('/', array('as' => 'home', 'uses' => 'HomeController@index'));
});
当我的数据库还没有表,并且我想进行php手工迁移时结果是:SQLSTATE[42S02]:找不到基表或视图:1146表"ae_dev.categories"不存在
我的迁移文件:
<?php
use Illuminate'Database'Schema'Blueprint;
use Illuminate'Database'Migrations'Migration;
class CreateCategoriesTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up() {
Schema::create('categories', function(Blueprint $table) {
$table->increments('id');
$table->integer('parent_id')->nullable()->index();
$table->integer('lft')->nullable()->index();
$table->integer('rgt')->nullable()->index();
$table->integer('depth')->nullable();
$table->string('name', 255);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::drop('categories');
}
}
我认为Laravel托盘从routes.php调用Category,并想做select或其他事情,所以我想运行创建categories表的迁移,但上面的错误是在。。。
我该怎么解决这个问题?
似乎所有的php artisan
命令都使用routes.php
文件,所以当您尝试在该文件中访问数据库表(因为您没有运行迁移,所以表不存在)时,您会收到此错误。由于出现此错误,您无法运行php artisan migrate
。
一种解决方案是删除查询数据库的代码,但这当然不是一个好的解决方案。所以,您应该做的是从您所做的第一次迁移中选择表(在您的情况下,它可能是categories
。稍后您会有更多的迁移,但这将是第一次),并添加类似的内容:
if (!Schema::hasTable('categories'))
{
return;
}
到您的routes.php
文件中。
然而,如果您将更多地使用迁移,并且还需要其他表来查询,则需要将上述条件更改为:
if (!Schema::hasTable('categories') || !Schema::hasTable('users'))
{
return;
}
但它仍然会引起一些问题——你不想每次在你的路线上运行这个代码,所以我会这样做:
if ($env == 'local') {
if (!Schema::hasTable('categories') || !Schema::hasTable('users'))
{
return;
}
}
当然,您需要配置您的环境。但现在您只在本地环境中运行此代码,在生产环境中,此代码不会运行,因此不会影响应用程序性能。当然,我在这里假设你不会在生产上和工匠一起玩。
编辑
但如果你只使用查询来共享数据(而不是路由),我会移动这些行:
View::share('roots', Category::roots()->get());
$tree = Category::get()->toHierarchy()->toArray();
View::share('categories', $tree);
到BaseController
,并在所有扩展它的控制器中运行方法(或父构造函数)。
旧答案(在这种情况下不够)
错误信息与您的解释非常清楚,您的数据库中还没有表。如果没有表,则无法运行数据库查询。
在迁移中,您应该创建必要的表,例如,这是用户表的迁移:
<?php
use Illuminate'Database'Schema'Blueprint;
use Illuminate'Database'Migrations'Migration;
class NewUser extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function ($table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('user_name', 60)->unique();
$table->string('email', 120)->unique();
$table->string('passwd', 256);
$table->decimal('balance', 8, 2);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
Schema::drop('users');
}
}
在使用迁移时,也不应该将数据插入数据库(现在可能会这样做)。您应该在对表进行种子设定时执行此操作。