这是我的ProductsTableSeeder,我将产品创建到products表中,并创建与目录的关系,创建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();
});
}发布于 2018-08-15 02:37:44
出现这个错误是因为数据库不是空的,并且您没有将属性传递给updateOrCreate()函数。因此,Laravel正在尝试创建一个新的。Check the API。
如果您只需将updateOrCreate()函数调整为:
Product::updateOrCreate(['id' => $i], [
'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);发布于 2018-08-12 00:25:03
尝试删除现有表,然后运行migrate。
https://stackoverflow.com/questions/51800769
复制相似问题