Laravel尝试播种不需要的列

时间:2018-11-02 09:48:15

标签: php laravel seeding laravel-seeding

我有一个奇怪的问题,一个小时的谷歌搜索和搜索stackoverflow并没有使我更接近解决方案。发生的事情是,当我尝试为表设置种子时(出于安全目的,我们将其称为my_table),种子器似乎试图填充我从未要求进行种子填充的列。

因此,首先我运行php artisan migrate使用以下迁移操作创建表:

<?php

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

class CreateMyTableTable extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('my_table', function (Blueprint $table) {
            $table->increments('id');

            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('user');

            $table->tinyInteger('from_default')->nullable(false)->default(7);
            $table->tinyInteger('to_default')->nullable(false)->default(20);
            $table->timestamps();

            $table->unique('user_id');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('my_table', function (Blueprint $table) {
            $table->dropUnique(['user_id']);
            $table->dropForeign(['user_id']);
        });
    }
}

这很好用,当我DESCRIBE my_table执行时,我得到以下信息:

Field           Type                Null    Key     Default     Extra
-------------------------------------------------------------------------------
id              int(10) unsigned    NO      PRI                 auto_increment
user_id         int(10) unsigned    NO      UNI     
from_default    tinyint(4)          NO              7
to_default      tinyint(4)          NO              20
created_at      timestamp           YES
updated_at      timestamp           YES

因此您可以看到该表是用我想要的迁移文件中的确切字段创建的。因此,现在我想使用以下种子为该表提供种子:

<?php

use App\DomainLogic\Models\MyTable;
use App\DomainLogic\Models\User;
use Faker\Factory as FakerFactory;
use Illuminate\Database\Seeder;

class MyTableTableSeeder extends Seeder
{
    /**
     * @var array list of MyTable Users
     */
    private $myTableUsers = [];

    /**
     * Run the database seeds.
     */
    public function run()
    {
        $this->createMyTableUsers();
        $myTableUsers = $this->getMyTableUsers();
        foreach ($myTableUsers as $myTableUser) {
            factory(MyTable::class)->create([
                'user_id' => $myTableUser->getKey(),
                'from_default' => 7,
                'to_default' => 20,
            ]);
        }
    }

    private function getMyTableUsers(): array
    {
        return $this->myTableUsers;
    }

    private function createMyTableUsers()
    {
        $faker = FakerFactory::create();

        // My table
        $this->myTableUsers[] = factory(User::class)->create([
            'id' => 2,
            'first_name' => 'Kalle',
            'last_name' => 'Andersson',
            'email' => 'kalle.andersson@email.com',
            'password' => bcrypt('password', ['rounds' => 4]),
            'mobile_number' => $faker->e164PhoneNumber,
        ]);
        $this->myTableUsers[] = factory(User::class)->create([
            'id' => 3,
            'first_name' => 'Johan',
            'last_name' => 'Petterson',
            'email' => 'johan.petterson@email.com',
            'password' => bcrypt('password', ['rounds' => 4]),
            'mobile_number' => $faker->e164PhoneNumber,
        ]);
        $this->myTableUsers[] = factory(User::class)->create([
            'id' => 4,
            'first_name' => 'Krister',
            'last_name' => 'Johansson',
            'email' => 'krister.johansson@email.com',
            'password' => bcrypt('password', ['rounds' => 4]),
            'mobile_number' => $faker->e164PhoneNumber,
        ]);
        $this->myTableUsers[] = factory(User::class)->create([
            'id' => 5,
            'first_name' => 'Daniel',
            'last_name' => 'Eriksson',
            'email' => 'daniel.eriksson@email.com',
            'password' => bcrypt('password', ['rounds' => 4]),
            'mobile_number' => $faker->e164PhoneNumber,
        ]);
    }
}

运行php artisan db:seed时出现此错误:

In Connection.php line 664:

  SQLSTATE[42S22]: Column not found: 1054 Unknown column 'starts_day_default' in 'field list' (SQL: insert into `my_table` (`user_id`, `starts_day_default`, `ends_day_default`, `from_default`, `to_default`) values (2, 07, 20, 7, 20))

In PDOConnection.php line 82:

  SQLSTATE[42S22]: Column not found: 1054 Unknown column 'starts_day_default' in 'field list'

In PDOConnection.php line 80:

  SQLSTATE[42S22]: Column not found: 1054 Unknown column 'starts_day_default' in 'field list'

所以奇怪的是,据我所知,我从未尝试填充名为starts_day_defaultends_day_default的列。因为这些列不存在,也不应该存在。实际情况是,这些列已重命名为starts_day_default -> from_defaultends _day_default -> to_default。用户创建正确,我可以在用户表中看到它们,所以这不是问题。这也是我的MyTable模型:

<?php

namespace App\DomainLogic\Models;

use DateTimeImmutable;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

class MyTable extends Model
{
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'my_table';

    /**
     * Creates personal trainer, if personal trainer with id exists.
     *
     * @param int $myTableId
     *
     * @return null|self
     */
    public static function createFromId(int $myTableId): ?self
    {
        $myTable = self::select('my_table.*')
            ->join('user', 'user.id', '=', 'my_table.user_id')
            ->where('my_table.id', '=', $myTableId)
            ->whereNull('user.anonymized_at')
            ->get()
            ->first();

        return $myTable;
    }

    /**
     * Create personal trainer, if user_id exists.
     *
     * @param int $userId
     *
     * @return null|MyTable
     */
    public static function createFromUserId(int $userId): ?self
    {
        return self::where('user_id', $userId)->get()->first();
    }

    /**
     * Gets all personal trainers.
     *
     * @param bool $active
     *
     * @return Collection
     */
    public static function getMyTables(bool $active = null): Collection
    {
        $query = self::select('my_table.*')
            ->join('user', 'user.id', '=', 'my_table.user_id')
            ->whereNull('user.anonymized_at');

        if (isset($active)) {
            $query->where('user.active', '=', $active);
        }

        $myTables = $query->get();

        return $myTables;
    }

    /**
     * Gets user.
     */
    public function getUser(): User
    {
        $user = $this->belongsTo(User::class, 'user_id', 'id')->getResults();

        return $user;
    }

    /**
     * Check if personal trainers ids are valid.
     *
     * @param array $myTableIds
     *
     * @return bool
     */
    public static function areMyTableIdsValid(array $myTableIds): bool
    {
        $dbMyTableIds = self::select('my_table.id')
            ->join('user', 'user.id', '=', 'my_table.user_id')
            ->whereIn('my_table.id', $myTableIds)
            ->whereNull('user.anonymized_at')
            ->get()
            ->pluck('id')
            ->toArray();

        $dbMyTableIds = array_map('intval', $dbMyTableIds);
        sort($myTableIds);
        sort($dbMyTableIds);

        $result = false;
        if ($myTableIds === $dbMyTableIds) {
            $result = true;
        }

        return $result;
    }
}

我尝试过

php artisan view:clear

php artisan cache:clear

php artisan debugbar:clear

composer dump-autoload

Unknown column 'username' in Laravel中建议,但这没有帮助。我删除了所有表并重新运行php artisan migrate,但这也无济于事。

我以前从未见过,所以我的问题是,有人可以看到我的问题吗?

2 个答案:

答案 0 :(得分:1)

最后解决了这个问题,我错过了一个工厂文件MyTableFactory仍然包含有问题的列的信息。该文件非常隐藏。

答案 1 :(得分:1)

就我而言,该文件位于数据库/工厂中。我建议任何有相同问题的人都搜索名称中带有Factory的所有文件,然后搜索每个发现的文件中引起该问题的列Ctrl+F