在创建过程中加载Laravel雄辩的关系

时间:2019-02-26 20:50:40

标签: php laravel orm eloquent

我已经阅读了https://laravel.com/docs/5.7/eloquent-relationships#eager-loading上的文档,但是仍然遇到问题。

该函数的403 Forbidden分支为什么不返回带有附加else的{​​{1}}对象?

\App\Models\Customer

这是它的测试,当前失败(\App\Models\Contact上的/** * * @param \App\Models\Contact $contact * @param string $msg * @return \App\Models\Customer */ public function createCustomerIfNecessary($contact, &$msg) { if ($contact->customer) { return $contact->customer; } else { $customer = new \App\Models\Customer(); $customer->setUuid(); $customer->contact_id = $contact->id; $customer->save(); $customer->loadMissing('contact'); $msg .= ' Created new customer with ID ' . $customer->id . '.'; return $customer; } } ):

ErrorException: Trying to get property 'id' of non-object

P.S。这种关系在我的代码的其他部分中起作用。

联系人模型具有:

$resultCustomer

并且客户模型具有:

public function testCreateCustomerIfNecessary() {
    $service = new \App\Services\OauthService();
    $msg = '';
    $contact = new \App\Models\Contact();
    $contactId = 654;
    $contact->id = $contactId;
    $resultCustomer = $service->createCustomerIfNecessary($contact, $msg);
    $this->assertEquals($contactId, $resultCustomer->contact->id);
}

“客户”表具有“ contact_id”外键。

1 个答案:

答案 0 :(得分:1)

啊,我在发布此问题后尝试的下一件事实际上似乎奏效了!

我将$customer->loadMissing('contact');替换为$customer->contact()->associate($contact);

现在测试通过了。