您只需要定义一个函数:
# 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');