代码之家  ›  专栏  ›  技术社区  ›  Endricho Folabessy

我在Laravel 10中的一对一关系有什么错误

  •  0
  • Endricho Folabessy  · 技术社区  · 9 月前

    我是拉拉维尔的新手。我尝试创建具有一对一关系的模型。 但当我去测试它时,它会给我一个错误:

    Illuminate\Database\QueryException:SQLSTATE[23000]:完整性 约束冲突:1452无法添加或更新子行:外部 关键点约束失败( belajar_laravel_eloquent wallets ,约束 wallets_customer_id_foreign 外键( customer_id )参考文献 customers ( id ))(连接:mysql,SQL:插入 钱包 ( amount , customer_id )值(5700000,0)

    怎么了?

    这是我的桌子:

    Schema::create('customers', function (Blueprint $table) {
                $table->string('id', 100)->primary();
                $table->string('name', 100);
                $table->string('email', 100)->unique('customer_email');
            });
    
    Schema::create('wallets', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('customer_id', 100);
            $table->bigInteger('amount')->default(0);
            $table->foreign('customer_id')->on('customers')->references('id');
        });
    

    这是我的模型:

    class Customer extends Model
    {
        public $timestamps = false;
        public function wallet(): HasOne
        {
            return $this->hasOne(Wallet::class, 'customer_id', 'id');
        }   
    }
    

    这是我的模型:

    class Wallet extends Model
    {
        public $timestamps = false;
    
        public function customer(): BelongsTo
        {
            return $this->BelongsTo(Customer::class, 'customer_id', 'id');
        }
    }
    

    这是我的测试:

    public function testOneToOneQueryRelation()
        {
            $customer = new Customer();
            $customer->id = 'Rinam';
            $customer->name = 'Rinam';
            $customer->email = 'RinamSayang@gmail.com';
            $customer->save();
    
            $wallet = new Wallet();
            $wallet->amount = 5700000;
    
            $customer->wallet()->save($wallet);
            self::assertNotNull($wallet->customer_id);
        }
    
    1 回复  |  直到 9 月前
        1
  •  0
  •   John Lobo    9 月前

    错误是因为您没有使用自动递增主键和键类型字符串,所以 Customer 模型设置了以下属性

    protected $keyType = 'string';
    public $incrementing = false;
    

    根据文件

    如果模型的主键不是整数,则应定义 受保护的$keyType属性。此属性应具有 字符串的值

    Eloquent假设主键是一个递增的整数 值,这意味着Eloquent将自动铸造主 一个整数的键。如果您希望使用非递增或 非数字主键必须定义一个公共$incrementing 设置为false的模型上的属性

    参考编号: Primary Keys