【发布时间】:2019-05-28 19:12:02
【问题描述】:
database/migrations/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(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),
];
});
routes/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) 价值观 (Vitae asperiores eligendi ipsam exercitationem quidem., 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))
【问题讨论】:
-
您不能将随机数用作
pid,因为它期望在产品表的 id 列中存在一个外键。 -
那么我如何将 pid 与它的源表关联起来?