我正在嘗試在類別和產品之間建立關系。我已經為這兩個表提供了各種列,并且我正在嘗試使用外部 id(類別表中的 category_id)鏈接它們,但我一直收到此錯誤。
違反完整性約束:1452 無法添加或更新子行:外鍵約束失敗違反完整性約束:1452 無法添加或更新子行,但無法回答問題
這是我的類別表
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
這是產品表
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('category_id');
$table->string('name');
$table->string('description');
$table->string('image');
$table->integer('price');
$table->foreign('category_id')
->references('id')
->on('categories')
->onDelete('cascade');
$table->timestamps();
});
}
這是類別模型。
class Category extends Model
{
use HasFactory;
protected $fillable = [
'name',
];
public function products()
{
return $this->hasMany(Product::class);
}
}
這是產品型號
class Product extends Model
{
use HasFactory;
protected $fillable = [
'name',
'description',
'image',
'price',
'category_id',
];
public function category()
{
return $this->belongsTo(Category::class);
}
public function setPriceAttribute($value)
{
$this->attributes['price'] = $value * 100;
}
}
這是我的產品工廠課程
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
class ProductFactory extends Factory
{
public function definition()
{
return [
'name'=>$this->faker->unique()->word(),
'description'=>$this->faker->text(),
'image'=>$this->faker->imageUrl(100, 100),
'price'=>$this->faker->numberBetween($min = 50, $max = 100),
'category_id'=>$this->faker->randomDigit()
];
}
}
這是我的資料庫播種機類
class DatabaseSeeder extends Seeder
{
public function run()
{
Product::factory(20)->create();
}
}
這是運行 db:seed 后我得到的完整錯誤代碼
INFO Seeding database.
照亮\資料庫\查詢例外
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`econs`.`products`, CONSTRAINT `products_category_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`) ON DELETE CASCADE) (SQL: insert into `products` (`name`, `description`, `image`, `price`, `category_id`, `updated_at`, `created_at`) values (omnis, Facere autem excepturi velit dolorem voluptas. Dignissimos laboriosam quia numquam sint harum officia eum. A aspernatur ratione fuga ut nesciunt sit. Ex nisi maxime quas., https://via.placeholder.com/100x100.png/006611?text=aut, 5700, 4, 2022-10-10 11:49:55, 2022-10-10 11:49:55))
at vendor/Laravel/framework/src/Illuminate/Database/Connection.php:759
755▕ // If an exception occurs when attempting to run a query, we'll format the error
756▕ // message to include the bindings with SQL, which will make this exception a
757▕ // lot more helpful to the developer instead of just the database's errors.
758▕ catch (Exception $e) {
? 759▕ throw new QueryException(
760▕ $query, $this->prepareBindings($bindings), $e
761▕ );
762▕ }
763▕ }
16 vendor frames
17 database/seeders/DatabaseSeeder.php:26
Illuminate\Database\Eloquent\Factories\Factory::create()
23 vendor frames
41 artisan:37
Illuminate\Foundation\Console\Kernel::handle()
uj5u.com熱心網友回復:
您正在使用$this->faker->randomDigit()
它創建一個亂數字,并且不在乎類別 ID 是否存在。對于您的工廠,您可以獲取一個隨機類別并使用它的 id:
'category_id'=>Category::inRandomOrder()->first()->id
uj5u.com熱心網友回復:
'category_id' => Category::inRandomOrder()->select("id")->first()->id ?? 1;
它只會以隨機順序獲取一個類別。之后給你 id 屬性,如果發生任何問題,那么它將插入 1 作為類別 id。但它不會通過任何例外。
uj5u.com熱心網友回復:
嘗試更改$table->unsignedInteger('category_id');
為 $table->unsignedBigInteger('category_id');
并確認類別表中存在類別 id 4
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/513606.html