我希望你沒事,我php artisan db:seed 在 laravel 9 中運行命令時遇到問題
錯誤
PDOException::("SQLSTATE[23000]: 完整性約束違規:1452 無法添加或更新子行:外鍵約束失敗 (
hunger-db.restaurants, CONSTRAINTrestaurants_user_id_foreignFOREIGN KEY (user_id) REFERENCESusers(id) ON DELETE CASCADE)")
setup_users_table
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('phone');
$table->tinyInteger('role_as')->default('0');
$table->tinyInteger('gender')->default('0');
$table->string('date_of_birth')->default('1999/9/9');
$table->rememberToken();
$table->timestamps();
});
}
setum_restaurants_table
public function up()
{
Schema::create('restaurants', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('img_src');
$table->string('description');
$table->string('minimum_order_amount');
$table->string('working_hours_open');
$table->string('working_hours_close');
$table->string('delivery_time');
$table->string('delivery_fee');
$table->boolean('status')->default('0');
$table->unsignedBigInteger('user_id')->default('1');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
}
用戶模型
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
protected $fillable = [
'name',
'email',
'password',
'phone',
];
public function orders()
{
return $this->hasMany(Order::class);
}
public function restaurants()
{
return $this->belongsTo(Restaurant::class);
}
}
餐廳模型
class Restaurant extends Model
{
use HasFactory;
protected $fillable = [
'name',
'img_src',
'description',
];
public function users()
{
return $this->belongsTo(User::class);
}
}
uj5u.com熱心網友回復:
我在這里看到了一些要改變的東西
setup_restaurants_table
我沒有很好地看到user_id默認值 1,也許在創建餐廳時定義值或手動將其分配給用戶 1 更好。
Schema::create('restaurants', function (Blueprint $table) {
$table->id();
...
$table->foreignId('user_id')->constrained()->onDelete('CASCADE');
});
資料庫更改運行后 php artisan migrate:fresh
用戶.php
應該改變與hasMany餐館的關系
public function restaurants()
{
return $this->hasMany(Restaurant::class);
}
播種
還要確保您的資料庫播種是正確的,我的意思是先創建用戶,然后再創建餐廳,并設定user_id現有值。
也許創建這樣的餐廳:
$user = User::factory()
->hasRestaurants(3)
->create();
如果任何工廠變更運行 php artisan db:seed
也可以查看Factory Retationship Docs
uj5u.com熱心網友回復:
檢查您已添加到餐廳表中的user_id 。確保它存在于用戶表中。也許我的英語不足以告訴你,可以檢查問題的另一個答案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/446170.html
標籤:php mysql 拉拉维尔 外键 laravel-9
上一篇:驗證來自api發布請求的欄位
