Laravel Virgin: установите заводскую последовательность, чтобы убедиться, что указанный набор данных был создан - PullRequest
0 голосов
/ 25 июня 2019

В моем приложении есть следующие миграции:

<?php

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

class CreateGridTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('grid', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedInteger('width');
            $table->unsignedInteger('height');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('grid');
    }
}
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRoverTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('rover', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('grid_id')->unsigned();
            $table->string('command');
            $table->foreign('grid_id')->references('id')->on('grid');
            $table->smallInteger('last_commandPos')->unsigned()->default(0);
            $table->smallInteger('grid_pos_x')->unsigned();
            $table->smallInteger('grid_pos_y')->unsigned();
            $table->enum('rotation', App\Constants\RoverConstants::ORIENTATIONS);
            $table->string('last_command');

            Schema::enableForeignKeyConstraints();
        });
    }

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

Создание таблиц grid и rover в явном виде.И я хочу заполнить данные через фабрику:

/** @var \Illuminate\Database\Eloquent\Factory $factory */
use App\Model\Grid;
use App\Model\Rover;
use App\Constants\RoverConstants;
use Faker\Generator as Faker;

/**
 * Random Command Generator based upon:
 * https://stackoverflow.com/a/13212994/4706711
 * @param integer $length How many characters the wommand will contain.
 * @return string
 */
function generateRandomCommand($length = 10): string {
    return substr(str_shuffle(str_repeat($x=implode('',RoverConstants::AVAILABLE_COMMANDS), ceil($length/strlen($x)) )),1,$length);
}

$factory->define(Grid::class,function(Faker $faker){
    return [
        'width'=>rand(1,10),
        'height'=>rand(1,10)
    ];
});

$factory->define(Rover::class, function(Faker $faker) {
    $command = generateRandomCommand(rand(0));
    $commandLength = strlen($command);
    $commandPos = rand(0,$commandLength);
    $lastExecutedCommand = substr($command,$commandPos,$commandPos);

    $randomGrid=Grid::inRandomOrder();

    return [
        'grid_id' => $randomGrid->value('id'),
        'grid_pos_x' => rand(0,$randomGrid->value('width')),
        'grid_pos_y' => rand(0,$randomGrid->value('height')),
        'rotation' => RoverConstants::ORIENTATION_EAST,
        'command' => $command,
        'last_commandPos' => $commandPos,
        'last_command' => $lastExecutedCommand,
    ];
});

Но как я могу гарантировать, что $randomGrid=Grid::inRandomOrder(); всегда будет возвращать Grid?Другими словами, я хочу проверить, нет ли сетки, а затем вызвать фабрику Grid, чтобы изготовить ее из фабрики Rover.

Вы знаете, как я могу это сделать?

1 Ответ

1 голос
/ 25 июня 2019

Ответа недостаточно, просто здесь для справки!

Если вы хотите быть уверенным, что там всегда есть сетка, вы можете создать ее (вызвать GridFactory) в этом месте.Если вы хотите использовать существующую сетку, вы можете переопределить этот атрибут.Вот так:

$factory->define(Rover::class, function(Faker $faker) {
    $command = generateRandomCommand(rand(0));
    $commandLength = strlen($command);
    $commandPos = rand(0,$commandLength);
    $lastExecutedCommand = substr($command,$commandPos,$commandPos);

    //This will create a second entry in the database.
    $randomGrid = factory(Grid::class)->create();

    return [
        'grid_id' => $randomGrid->id, //no need for the value() method, they are all attributes
        'grid_pos_x' => rand(0,$randomGrid->width), 
        'grid_pos_y' => rand(0,$randomGrid->height),
        'rotation' => RoverConstants::ORIENTATION_EAST,
        'command' => $command,
        'last_commandPos' => $commandPos,
        'last_command' => $lastExecutedCommand,
    ];
});

Над фабрикой показана сетка, создаваемая на лету, когда вызывается RoverFactory.Создание нового ровера с factory(Rover::class)->create() также создаст новую сетку (и сохранит ее).Теперь, если вы хотите использовать существующую сетку, вы можете сделать следующее:

factory(Rover::class)->create([
    'grid_id' => $existingGrid->id,
    'grid_pos_x' => rand(0, $existingGrid->width),
    'grid_pos_y' => rand(0, $existingGrid->height),
]);

Это создаст ровер с существующей сеткой (которую вы, возможно, создали ранее с помощью GridFactory или чего-то еще. Надеюсь, это сработаетдля вас. Наслаждайтесь Laravel!

Редактировать:

Обычно вы делаете что-то вроде этого:

$factory->define(Rover::class, function(Faker $faker) {
    $command = generateRandomCommand(rand(0));
    $commandLength = strlen($command);
    $commandPos = rand(0,$commandLength);
    $lastExecutedCommand = substr($command,$commandPos,$commandPos);

    return [
        'grid_id' => function() {
            return factory(Grid::class)->create()->id;
        }
        'grid_pos_x' => '', //But then i got nothing for this.
        'grid_pos_y' => '', //But then i also got nothing for this.
        'rotation' => RoverConstants::ORIENTATION_EAST,
        'command' => $command,
        'last_commandPos' => $commandPos,
        'last_command' => $lastExecutedCommand,
    ];
});
...