Подтвердить что ты не робот

База данных Laravel 4 migrate не найдена

Я пытаюсь сделать следующий учебник: https://medium.com/on-coding/e8d93c9ce0e2

Когда дело доходит до запуска:

php artisan migrate

Я получаю следующую ошибку:

[Exception]                                                                        
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'laravel.user' doesn't   
exist (SQL: alter table `user` add `id` int unsigned not null auto_increment prim  
ary key, add `username` varchar(255) null, add `password` varchar(255) null, add   
`email` varchar(255) null, add `created_at` datetime null, add `updated_at` datet  
ime null) (Bindings: array (                                                       
))

Соединение с базой данных работает, таблица миграции была успешно создана. Имя базы данных было изменено, как вы можете видеть в сообщении об ошибке.

Что-то странное для меня, это то, что он пытается изменить таблицу - которая не существует - и не создавать ее.

Вот мои другие файлы, такие как UserModel, Seeder, Migtation и DB Config.

CreateUserTable:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUserTable extends Migration {

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('user', function(Blueprint $table)
    {

        $table->increments("id");

        $table
            ->string("username")
            ->nullable()
            ->default(null);
        $table
            ->string("password")
            ->nullable()
            ->default(null);
        $table
            ->string("email")
            ->nullable()
            ->default(null);
        $table
            ->dateTime("created_at")
            ->nullable()
            ->default(null);
        $table
            ->dateTime("updated_at")
            ->nullable()
            ->default(null);

    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('user', function(Blueprint $table)
    {
        Schema::dropIfExists("user");
    });
}

}

UserModel:   

use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

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

/**
 * The attributes excluded from the model JSON form.
 *
 * @var array
 */
protected $hidden = array('password');

/**
 * Get the unique identifier for the user.
 *
 * @return mixed
 */
public function getAuthIdentifier()
{
    return $this->getKey();
}

/**
 * Get the password for the user.
 *
 * @return string
 */
public function getAuthPassword()
{
    return $this->password;
}

/**
 * Get the e-mail address where password reminders are sent.
 *
 * @return string
 */
public function getReminderEmail()
{
    return $this->email;
}

}

UserSeeder:   

class UserSeeder extends DatabaseSeeder
{
public function run()
{
    $users = [
        [
            "username" => "ihkawiss",
            "password" => Hash::make("123456"),
            "email"    => "[email protected]"
        ]
    ];

    foreach ($users as $user)
    {
        User::create($user);
    }
}
}

DatabaseSeeder:   

class DatabaseSeeder extends Seeder {

/**
 * Run the database seeds.
 *
 * @return void
 */
public function run()
{
    Eloquent::unguard();

    $this->call('UserSeeder');
}

}

Конфигурация базы данных:   

return array(

/*
|--------------------------------------------------------------------------
| PDO Fetch Style
|--------------------------------------------------------------------------
|
| By default, database results will be returned as instances of the PHP
| stdClass object; however, you may desire to retrieve records in an
| array format for simplicity. Here you can tweak the fetch style.
|
*/

'fetch' => PDO::FETCH_CLASS,

/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/

'default' => 'mysql',

/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/

'connections' => array(

    'sqlite' => array(
        'driver'   => 'sqlite',
        'database' => __DIR__.'/../database/production.sqlite',
        'prefix'   => '',
    ),

    'mysql' => array(
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'laravel',
        'username'  => 'root',
        'password'  => '',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ),

    'pgsql' => array(
        'driver'   => 'pgsql',
        'host'     => 'localhost',
        'database' => 'database',
        'username' => 'root',
        'password' => '',
        'charset'  => 'utf8',
        'prefix'   => '',
        'schema'   => 'public',
    ),

    'sqlsrv' => array(
        'driver'   => 'sqlsrv',
        'host'     => 'localhost',
        'database' => 'database',
        'username' => 'root',
        'password' => '',
        'prefix'   => '',
    ),

),

/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk have not actually be run in the databases.
|
*/

'migrations' => 'migrations',

/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer set of commands than a typical key-value systems
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/

'redis' => array(

    'cluster' => true,

    'default' => array(
        'host'     => '127.0.0.1',
        'port'     => 6379,
        'database' => 0,
    ),

),

);

Надеюсь, кто-нибудь может дать мне подсказку.

С наилучшими пожеланиями, ihkawiss

4b9b3361

Ответ 1

В вашем файле миграции CreateUserTable вместо Schema::table вы должны использовать Schema::create.

Schema::table используется для изменения существующей таблицы, а Schema::create используется для создания новой таблицы.

Проверьте документацию:

Таким образом, ваша миграция будет:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUserTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('user', function(Blueprint $table) {
        {

            $table->increments("id",true);
            $table->string("username")->nullable()->default(null);
            $table->string("password")->nullable()->default(null);
            $table->string("email")->nullable()->default(null);
            $table->timestamps();

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists("user");
    }

}

Ответ 2

Основная причина этого может заключаться в том, что синтаксис, используемый для создания миграции php artisan migrate ..., не совсем корректен. В этом случае --create не будет правильно поднят, и вы увидите Schema::table вместо ожидаемого Schema::create. Когда файл миграции создается таким образом, вы также можете пропустить некоторые другие маркеры для миграции создания, такие как $table->increments('id'); и $table->timestamps();

Например, эти две команды не будут создавать файл миграции таблицы создания, как вы могли ожидать:

php artisan migrate:make create_tasks_table --table="tasks" --create
php artisan migrate:make create_tasks2_table --table=tasks2 --create

Однако команда не сработает с ошибкой. Вместо этого laravel создаст файл миграции, используя Schema::table

Я всегда использую полный синтаксис при создании нового файла миграции следующим образом:

php artisan migrate:make create_tasks_table --table=tasks --create=tasks 

чтобы избежать таких проблем.

Ответ 3

Иногда это вызвано пользовательскими командами мастеров. Некоторые из этих команд могут инициировать несколько классов. И поскольку мы сделали откат, таблица не найдена. Проверьте пользовательские команды ремесленника. Вы можете прокомментировать строки, вызывающие триггер. Запустите команду php artisan migrate, а затем раскомментируйте. Это то, что я должен был сделать.