我已经阅读了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”外键。
答案 0 :(得分:1)
啊,我在发布此问题后尝试的下一件事实际上似乎奏效了!
我将$customer->loadMissing('contact');
替换为$customer->contact()->associate($contact);
现在测试通过了。