Laravel工厂深度嵌套关系失败



我遇到一个问题,具有深度嵌套关系的工厂由于DB外键错误而无法正确执行。

我有一系列工厂,用于通过应用程序模型将数据传播到数据库中。当我经营所有基层(没有关系的工厂(工厂时,我没有问题。当我运行所有的单层工厂(具有单一关系的工厂(时,我没有问题。然而,当我运行任何二级工厂(与另一个工厂有关系的工厂(时,我会得到DB错误。

简单地说,这意味着我可以毫无问题地运行ProductKeyFactoryActivationCodeFactory。只有当我尝试运行FeatureActivationFactory时才会发生这种情况

我的工厂

class FeatureActivationFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = FeatureActivation::class;
/** @var string $connection DB Connection */
protected $connection = License::DB;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'code_id' => ActivationCode::factory(),
'productSoftware_id' => ProductSoftware::factory(),
'date' => now()
];
}
}
class ActivationCodeFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = ActivationCode::class;
/** @var string $connection DB Connection */
protected $connection = License::DB;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'key_id' => ProductKey::factory(),
'code' => $this->faker->lexify('??????????'),
'isActive' => 0
];
}
}
class ProductKeyFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = ProductKey::class;
/** @var string $connection DB Connection */
protected $connection = License::DB;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'name' => $this->faker->unique->word,
'startDate' => now(),
'endDate' => $this->faker->dateTimeThisYear()
];
}
}

我的工厂错误FeatureActivation::factory()->create();:

删除了不正确的错误消息

编辑

感谢大家指出我的愚蠢错误。是的,这是我收到的一个错误,因为名字重复,但这并不是我最终得到的错误。感谢您指出unique功能—我添加它是为了避免出现错误。请参阅下面的正确错误消息:

Illuminate/Database/QueryException with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`license`.`activationCodes`, CONSTRAINT `FK_ActivationCodes_KeyID` FOREIGN KEY (`key_id`) REFERENCES `activationCodes` (`id`) ON DELETE RESTRICT) (SQL: insert into `activationCodes` (`key_id`, `code`, `isActive`) values (18, zvszgdrrlj, 0))'

如果必须处理唯一索引,则需要告诉Faker避免生成相同的月份名称。

class ProductKeyFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = ProductKey::class;
/** @var string $connection DB Connection */
protected $connection = License::DB;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'name' => $this->faker->unique()->monthName,
'startDate' => now(),
'endDate' => $this->faker->dateTimeThisYear()
];
}
}

这是由于我的错误造成的。嵌套关系确实有效,但是,重要的是要测试模型中声明的任何关系,以确保它们正确工作,尤其是在使用更复杂的关系(如hasOnThrough等(时,尤其是与不完全遵循laravel/雄辩命名约定的列相结合时。

相关内容

  • 没有找到相关文章

最新更新