数据库/迁移/2018_12_20_022430_create_products_table.php
> class CreateProductsTable extends Migration {
> /**
> * Run the migrations.
> *
> * @return void
> */
> public function up()
> {
> Schema::create('products', function (Blueprint $table) {
> $table->increments('id');
> $table->string ('name');
> $table->text('description');
> $table->decimal('price');
> $table->string('file');
> $table->timestamps();
> });
> }
数据库/迁移/2018_12_20_042857_create_cards_table.php
class CreateCardsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('cards', function (Blueprint $table) {
$table->increments('id');
$table->string ('quantity');
$table->string('status');
$table->integer('pid')->unsigned();
$table->foreign('pid')->references('id')->on('products');
$table->integer('cid')->unsigned();
$table->foreign('cid')->references('id')->on('customers');
$table->timestamps();
});
}
数据库/工厂/UserFactory.php
$factory->define(AppProduct::class, function (Faker $faker) {
return [
//'id'=>$faker->numberBetween($min = 1, $max = 20),
'name'=> $faker->word,
'description'=> $faker->sentence($nbWords = 6, $variableNbWords = true),
'price' => $faker->randomFloat($nbMaxDecimals = 100, $min = 1, $max = 10),
'file' => $faker->imageUrl($width = 640, $height = 480),
];
});
$factory->define(AppCard::class, function (Faker $faker) {
return [
//'id'=>$faker->numberBetween($min = 1, $max = 20),
'quantity'=>$faker->sentence($nbWords = 6, $variableNbWords = true),
'status'=>$faker->boolean($chanceOfGettingTrue = 10),
'cid'=>$faker->numberBetween($min = 1, $max = 20),
'pid'=>$faker->numberBetween($min = 1, $max = 20),
];
});
路由/web.php
factory(AppProduct::class,5)->create();
factory(AppCard::class,5)->create();
终端:
$ php artisan db:seed
错误:
In Connection.php第664行:SQLSTATE[23000]:完整性约束冲突:1452无法添加或更新子行:外键约束失败(
food
.cards
,约束ca rds_pid_foreign
外键(pid
)参考products
(id
))(SQL:插入cards
(quantity
、status
、cid
、pid
、updated_at
、creat ed_at
)值(Vitae asperiores eligendi ipsam exercationem quidem.,1,
18,82019-01-02 04:22:102019-01-02 104:22:10)在Connection.php第458行中:SQLSTATE[23000]:完整性约束冲突:1452无法添加或更新子行:外键约束失败(
food
.cards
,约束ca rds_pid_foreign
外键(pid
)参考文献products
(id
)
您必须使用产品和客户的ID,而不是随机数:
$factory->define(AppCard::class, function (Faker $faker) {
$p_ids = AppProduct::pluck('id')->toArray();
$c_ids = AppCustomer::pluck('id')->toArray();
return [
//'id'=>$faker->numberBetween($min = 1, $max = 20),
'quantity'=>$faker->sentence($nbWords = 6, $variableNbWords = true),
'status'=>$faker->boolean($chanceOfGettingTrue = 10),
'cid'=>$faker->randomElement($c_ids),
'pid'=> $faker->randomElement($p_ids),
];
});
简而言之,从products
和customers
表中选择所有id,并从中取一个随机值作为外键。
但要确保你的工厂按照特定的顺序,所以CardFactory
必须在ProductFactory
和CustomerFactory
之后被解雇。
如果pid
具有随机值,但数据库不会在cards table
中为pid
输入products table
中不存在的值。插入到CCD_ 29中的值必须存在于CCD_。