AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 79186436
Accepted
Anthonyx82
Anthonyx82
Asked: 2024-11-14 03:48:26 +0800 CST2024-11-14 03:48:26 +0800 CST 2024-11-14 03:48:26 +0800 CST

O semeador Laravel não preenche a tabela com chaves estrangeiras

  • 772

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 vehiclestabela, há uma chave estrangeira referenciando a customerstabela. 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 vehiclestabela 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

  • 1 1 respostas
  • 32 Views

1 respostas

  • Voted
  1. Best Answer
    premod suraweera
    2024-11-14T06:01:45+08:002024-11-14T06:01:45+08:00

    Fiz isso em um projeto anterior e funcionou. Vou corrigir seu código e mostrar a você. Está quase correto. Tente.

    public function up(): void
    {
     Schema::create('vehicles', function (Blueprint $table){
        $table->id('vehicle_id');
        $table->unsignedBigInteger('customer_id');
        $table->foreign('customer_id')->references('customer_id')->on('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();
      }
    }
    

    agora você pode executar uma migração

    php artisan migrate:fresh --seed
    
    • 1

relate perguntas

  • Adicionar número de série para atividade de cópia ao blob

  • A fonte dinâmica do empacotador duplica artefatos

  • Selecione linhas por grupo com 1s consecutivos

  • Lista de chamada de API de gráfico subscritoSkus estados Privilégios insuficientes enquanto os privilégios são concedidos

  • Função para criar DFs separados com base no valor da coluna

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle?

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Quando devo usar um std::inplace_vector em vez de um std::vector?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Martin Hope
    Aleksandr Dubinsky Por que a correspondência de padrões com o switch no InetAddress falha com 'não cobre todos os valores de entrada possíveis'? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer Quando devo usar um std::inplace_vector em vez de um std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB Por que o GCC gera código que executa condicionalmente uma implementação SIMD? 2024-02-17 06:17:14 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve