Ответа недостаточно, просто здесь для справки!
Если вы хотите быть уверенным, что там всегда есть сетка, вы можете создать ее (вызвать 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,
];
});