php - Laravel:同一张表,一对一的关系
问题描述
我有一个带有配偶字段的客户表,我引用该外键:
$table->integer('spouse')->nullable();
$table->foreign('spouse')->references('customerId')->on('customers');
我的问题是,我如何设置函数返回belongsTo()
,hasOne()
如果我只能有一个名为的函数spouse()
:
public function spouse()
{
return $this->hasOne('App\Customer');
}
谢谢。
解决方案
您只需要定义一个函数:
# Customer.php
public function spouse()
{
return $this->hasOne('App\Customer');
}
然后,当链接对象时,将对象相互关联:
# CustomersController.php
$person_a = Customer::find(1);
$person_b = Customer::find(2);
$person_a->spouse()->save($person_b);
$person_b->spouse()->save($person_a);
然后使用它:
# CustomersController.php
$person_a = Customer::find(1);
$person_b = $person_a->spouse;
$person_a = $person_b->spouse;
观察
当定义与 不同的外键的关系时{model}_id
,您需要在定义关系时指定它(查看文档):
# Customer.php
public function spouse()
{
return $this->hasOne('App\Customer', 'spouse');
}
此外,这个外键列需要是unsignedInteger()
(如果主键是 a integer
)或者bigUnsignedInteger()
如果外键是bigInteger
:
如果:
$table->increments('customerId');
做:
$table->unsignedInteger('spouse')->nullable();
$table->foreign('spouse')->references('customerId')->on('customers');
或者如果:
$table->bigIncrements('customerId');
做:
$table->unsignedBigInteger('spouse')->nullable();
$table->foreign('spouse')->references('customerId')->on('customers');
推荐阅读
- angular - 在 Angular 9 应用程序中获得循环依赖
- r - R(寓言包)中的预测:寓言中的准确度函数找不到 y 变量
- ffmpeg - 处理输入时发现无效数据。没有找到起始码
- python-3.x - 如何从python中的其他函数访问变量
- module - 通过运行带有 -m 选项的 python,使用 bokeh image_url 绘制本地图像
- c# - 每当您得分时,Unity 都会增加更多时间
- date - 如何使用整数算术将儒略日期转换为不同的表示形式和从不同的表示形式转换出来
- python - 返回 DateTimeField 会导致 OperationError
- mysql - Mysqldump 不会导出所有数据库
- c# - 从不同的应用程序访问文件 - Xamarin iOS