Laravel:同一张表,一对一关系

时间:2019-04-30 01:19:45

标签: php sql laravel eloquent

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

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

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

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

谢谢。

1 个答案:

答案 0 :(得分:0)

您只需要定义一个功能:

# 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不同的外键定义关系时,需要在定义关系时指定它(检查docs):

# Customer.php

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

此外,此外键列需要为unsignedInteger()(如果主键为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');