首页 > 解决方案 > Laravel:同一张表,一对一的关系

问题描述

我有一个带有配偶字段的客户表,我引用该外键:

$table->integer('spouse')->nullable();
$table->foreign('spouse')->references('customerId')->on('customers');

我的问题是,我如何设置函数返回belongsTo()hasOne()如果我只能有一个名为的函数spouse()

public function spouse()
{
    return $this->hasOne('App\Customer');
}

谢谢。

标签: phpsqllaraveleloquent

解决方案


您只需要定义一个函数:

# 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');

推荐阅读