数据库/迁移/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();
});
}
database / 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),
];
});
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
))
答案 0 :(得分:0)
您必须使用产品和客户的ID代替随机数:
$factory->define(App\Card::class, function (Faker $faker) {
$p_ids = App\Product::pluck('id')->toArray();
$c_ids = App\Customer::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
。
答案 1 :(得分:0)
如果pid
具有随机值,但是数据库不会在pid
中不存在的cards table
中输入products table
的值。在pid
中插入的值必须在product id
中存在。