Вам нужно будет определить только одну функцию:
# 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');