我读过https://laravel.com/docs/5.7/eloquent-relationships#eager-loading的文件,但仍有困难。
为什么此函数的ther
分支不返回带有附加的\App\Models\Client
对象?
/**
*
* @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:试图在
$resultCustomer
上获取非对象的属性“id”):
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);
}
另外,这种关系在我的代码的其他部分也起作用。
联系人模型具有:
public function customer() {
return $this->hasOne('App\Models\Customer');
}
客户模型具有:
public function contact() {
return $this->belongsTo('App\Models\Contact');
}
“customers”表有一个“contact_id”外键。
啊,我在发布这个问题后尝试的下一件事似乎真的奏效了!
我替换了$customer-
现在测试通过了。