我是拉拉维尔的新手。我尝试创建具有一对一关系的模型。
但当我去测试它时,它会给我一个错误:
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);
}