Estou trabalhando em um projeto Laravel e tenho as seguintes migrações:
public function up(): void
{
Schema::create('customers', function (Blueprint $table) {
$table->id('customer_id');
$table->string('first_name', 50);
$table->string('last_name', 50);
$table->string('address', 100)->nullable();
$table->string('phone', 15)->nullable();
$table->string('email', 50)->unique();
$table->timestamp('registration_date')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('customers');
}
public function up(): void
{
Schema::create('vehicles', function (Blueprint $table) {
$table->id('vehicle_id');
$table->foreignId('customer_id')->constrained('customers')->onDelete('cascade');
$table->string('make', 50);
$table->string('model', 50);
$table->year('year');
$table->string('license_plate', 15)->unique();
$table->string('vin', 17)->unique();
$table->string('color', 20)->nullable();
$table->timestamp('registration_date')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('vehicles');
}
Como você pode ver na vehicles
tabela, há uma chave estrangeira referenciando a customers
tabela. Vou mostrar a você o relacionamento nos modelos:
class Vehicle extends Model
{
use HasFactory;
/**
* The primary key associated with the table.
*
* @var string
*/
protected $primaryKey = 'vehicle_id';
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'customer_id',
'make',
'model',
'year',
'license_plate',
'vin',
'color',
'registration_date',
];
public function customer(): BelongsTo
{
return $this->belongsTo(Customer::class, 'customer_id');
}
}
class Customer extends Model
{
use HasFactory;
/**
* The primary key associated with the table.
*
* @var string
*/
protected $primaryKey = 'customer_id';
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'first_name',
'last_name',
'address',
'phone',
'email',
'registration_date',
];
public function vehicles(): HasMany
{
return $this->hasMany(Vehicle::class, 'customer_id');
}
}
E finalmente, as fábricas:
class CustomerFactory extends Factory
{
protected $model = Customer::class;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'first_name' => fake()->name(),
'last_name' => fake()->lastName(),
'address' => fake()->address(),
'phone' => fake()->phoneNumber(),
'email' => fake()->email(),
'registration_date' => fake()->date(),
];
}
}
class VehicleFactory extends Factory
{
protected $model = Vehicle::class;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'customer_id' => Customer::factory(),
'make' => fake()->company,
'model' => fake()->word,
'year' => fake()->year,
'license_plate' => strtoupper(fake()->unique()->bothify('???-####')),
'vin' => strtoupper(fake()->unique()->bothify('?????????????????')),
'color' => fake()->safeColorName,
'registration_date' => fake()->date(),
];
}
}
Aparentemente, o seguinte erro está ocorrendo:
SQLSTATE[HY000]: General error: 1 foreign key mismatch - "vehicles" referencing "customers" (Connection: sqlite, SQL: insert into "vehicles" ("customer_id", "make", "model", "year", "license_plate", "vin", "color", "registration_date", "updated_at", "created_at") values (11, Wilderman Group, nostrum, 1970, VRF-4423, FVKRDKQWQHGDVFWBP, purple, 2019-01-16, 2024-11-13 18:30:33, 2024-11-13 18:30:33))
Este erro é devido à tentativa de adicionar uma chave estrangeira na vehicles
tabela para um cliente com ID 11, que claramente não existe porque apenas 10 clientes são criados para 15 veículos. Tentei "forçar" o erro a desaparecer fazendo um loop por todos os veículos criados e atribuindo-os a clientes existentes, mas isso levou a outro erro. Acho que provavelmente há algo errado aqui que seria muito mais simples de consertar do que tentar resolver de uma forma para a qual o framework não foi projetado. Se alguém souber o que pode estar errado, agradeceria a ajuda.
PS: Estou usando o Laravel 11
Fiz isso em um projeto anterior e funcionou. Vou corrigir seu código e mostrar a você. Está quase correto. Tente.
agora você pode executar uma migração