Populating a database in a Laravel migration file

前端 未结 7 1882
不知归路
不知归路 2020-12-07 10:31

I\'m just learning Laravel, and have a working migration file creating a users table. I am trying to populate a user record as part of the migration:

public          


        
7条回答
  •  执念已碎
    2020-12-07 11:24

    I tried this DB insert method, but as it does not use the model, it ignored a sluggable trait I had on the model. So, given the Model for this table exists, as soon as its migrated, I figured the model would be available to use to insert data. And I came up with this:

    public function up() {
            Schema::create('parent_categories', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('name');
                $table->string('slug');
                $table->timestamps();
            });
            ParentCategory::create(
                [
                    'id' => 1,
                    'name' => 'Occasions',
                ],
            );
        }
    

    This worked correctly, and also took into account the sluggable trait on my Model to automatically generate a slug for this entry, and uses the timestamps too. NB. Adding the ID was no neccesary, however, I wanted specific IDs for my categories in this example. Tested working on Laravel 5.8

提交回复
热议问题