在创建过程中加载Laravel雄辩的关系 [英] Load Laravel Eloquent relationship during creation

查看:54
本文介绍了在创建过程中加载Laravel雄辩的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've read the docs at https://laravel.com/docs/5.7/eloquent-relationships#eager-loading but am still having trouble.

为什么此函数的else分支不返回带有附加\App\Models\Contact\App\Models\Customer对象?

Why does the else branch of this function not return a \App\Models\Customer object with an attached \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;
    }
}

这是它的测试,当前失败($resultCustomer上的ErrorException: Trying to get property 'id' of non-object):

Here is its test, which currently fails (ErrorException: Trying to get property 'id' of non-object on $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);
}

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

P.S. The relationship works in other parts of my code.

联系人模型具有:

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

并且客户模型具有:

public function contact() {
    return $this->belongsTo('App\Models\Contact');
}

客户"表具有"contact_id"外键.

And the 'customers' table has a 'contact_id' foreign key.

推荐答案

啊,我在发布此问题后尝试的下一个方法似乎确实有效!

Ahhh, the next thing I tried after posting this question actually seems to work!

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

现在测试通过了.

这篇关于在创建过程中加载Laravel雄辩的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆