Laravel: та же таблица, отношения один-к-одному - PullRequest
0 голосов
/ 30 апреля 2019

У меня есть таблица клиентов с полем супруга, я ссылаюсь на этот внешний ключ с помощью:

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

Моя проблема в том, как настроить функцию на возврат belongsTo() и hasOne(), если у меня может быть только одна функция с именем spouse():

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

Спасибо.

1 Ответ

0 голосов
/ 30 апреля 2019

Вам нужно будет определить только одну функцию:

# 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');
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...