【发布时间】:2019-01-18 21:52:10
【问题描述】:
这是我的产品TableSeeder 我将产品创建到产品表中并与类别的关系 创建 category_product 表并为其添加外键。
我在迁移和播种它说重复的数据时出错。 我该如何解决?
use App\Product;
use Illuminate\Database\Seeder;
class ProductsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//
//Product::truncate();
for($i = 1; $i <= 10; $i++){
Product::updateOrCreate([
'name'=> 'Laptop'.$i,
'slug' => 'laptop'.$i,
'details' => [13,14,15][array_rand([13,14,15])].'inch,'.[1,2,3][array_rand([1,2,3])].'TB SSD,32GB RAM',
'price' => rand(1500,3000),
'description' => 'Lorem'.$i.' ipsum dolor sit amet, consectetur adipiscing elit. Maecenas fermentum. laoreet turpis, nec sollicitudin dolor cursus at. Maecenas aliquet, dolor a faucibus efficitur, nisi tellus cursus urna, eget dictum lacus turpis.',
])->categories()->attach(1);
}
$product = Product::find(1)-> categories()->attach(2);
}
这是产品表。
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->string('slug')->unique();
$table->string('details')->nullable();
$table->float('price');
$table->text('description');
//$table->integer('category_id');
$table->timestamps();
});
}
这是类别表。
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->string('slug')->unique();
$table->timestamps();
});
}
这是关系表。
public function up()
{
Schema::create('category_product', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id')->unsigned()->nullable();
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->integer('category_id')->unsigned()->nullable();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->timestamps();
});
}
【问题讨论】:
-
运行种子时表是空的吗?尝试
php artisan migrate:refresh然后php artisan db:seed。另一件需要注意的事情是,当您附加到类别 1(在 for 内部)和 2(在 for 之后)时,这些类别不存在,如果从空数据库播种,您需要先创建这些类别. -
我都试过了
-
没有错误运行 php artisan migrate:refresh db:seed 时出现此错误
-
好的,如果您尝试刷新但仍然无法正常工作,请尝试以下操作:
php artisan migrate:refresh然后转到您的数据库管理器并执行SELECT * FROM products;让我们知道表是否为空。同时让我们知道您的迁移中的 down() 方法。 -
现在我有这个错误!Illuminate\Database\QueryException:SQLSTATE[23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败(
onetech.@987654330 @, CONSTRAINTcategory_product_category_id_foreignFOREIGN KEY (category_id) REFERENCEScategories(id) ON DELETE CASCADE) (SQL: insert intocategory_product(category_id,product_id) 值 (1, 1))
标签: php laravel web laravel-5.6