【发布时间】:2019-06-25 08:38:34
【问题描述】:
在我的应用程序中,我有以下迁移:
<?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 工厂从Rover 工厂制作一个。
你知道我该怎么做吗?
【问题讨论】:
-
我建议你总是创建一个新的网格。如果您想使用现有网格,请在生成
Rover但不在工厂中时执行此操作,例如factory(Rover::class)->make([ 'grid_id' => x])
标签: laravel-5 eloquent factory