数据库/迁移/2018\u 12\u 20\u 022430\u创建\u产品\u表.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\u 12\u 20\u 042857\u创建\u卡片\u表格.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();
});
}
数据库/factories/userfactory.php
$factory->define(App\Product::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(App\Card::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(App\Product::class,5)->create();
factory(App\Card::class,5)->create();
终端:
$ php artisan db:seed
错误:
在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
)价值观(简历1,
18, 8, 2019-01-02 04:22:10, 2019-01-02 04:22:10))
在connection.php第458行中:sqlstate[23000]:完整性约束冲突:1452无法添加或更新子行:外键约束失败( food
. cards
,约束 ca rds_pid_foreign
外键( pid
)参考文献 products
( id
))
2条答案
按热度按时间gdx19jrr1#
您必须使用产品和客户的id,而不是随机数字:
简而言之,从中选择所有ID
products
以及customers
表,并从中获取一个随机值以将其用作外键。但要确保你们的工厂有明确的顺序,所以
CardFactory
必须在ProductFactory
以及CustomerFactory
.6rqinv9w2#
如果
pid
具有随机值,但数据库将不会输入值pid
在cards table
这在世界上是不存在的products table
. 插入的值pid
必须存在于product id
.