即使数据库中的数据正确,Laravel雄辩的关系对象也会过时

时间:2018-12-09 23:02:29

标签: laravel laravel-5 eloquent

我正在使用Laravel 5.7,并且在两个雄辩的模型之间有一个one-to-one relationship

我有一个运行良好的简单函数,正确的值一直保存到数据库中:

public function saveMarketingOriginInfo(Contact $contact, $data) {
    $contact->marketingOrigin()->create($data);        
    $this->makeOtherChangesByReference($contact->marketingOrigin);
    $contact->marketingOrigin->save();
    return $contact->marketingOrigin; 
}

但是,当为它编写功能测试时,我注意到它返回的对象是陈旧的(其属性中没有正确的值)。

仅当我将return语句更改为return \App\Models\MarketingOrigin::find($contact->id);时,我的测试才通过。

(MarketingOrigin使用“ contact_id”作为主键。)

我在做什么错?

如何在不进行数据库读取查询($contact->marketingOrigin->save();)的情况下返回刚刚保存在上一行(find())中的同一对象?


更新以回复评论:

protected $table = 'marketing_origins';//MarketingOrigin class
protected $primaryKey = 'contact_id';
protected $guarded = [];
public function contact() {
    return $this->belongsTo('App\Models\Contact');
}

测试:

public function testSaveMarketingOriginInfo() {
    $helper = new \App\Helpers\SignupHelper();
    $contactId = 92934;
    $contact = factory(\App\Models\Contact::class)->create(['id' => $contactId]);
    $leadMagnetType = 'LMT';
    $audience = 'a60907';
    $hiddenMktgFields = [
        'audience' => $audience,
        'leadMagnetType' => $leadMagnetType
    ];
    $result = $helper->saveMarketingOriginInfo($contact, $hiddenMktgFields);
    $this->assertEquals($result->contact_id, $contactId, 'contact_id did not get saved');
    $this->assertEquals($result->campaignId, '6075626793661');
    $this->assertEquals($result->leadMagnetType, $leadMagnetType);
    $marketingOrigin = \App\Models\MarketingOrigin::findOrFail($contactId);
    $this->assertEquals($marketingOrigin->adsetId, '6088011244061');
    $this->assertEquals($marketingOrigin->audience, $audience);
    $this->assertEquals($marketingOrigin, $result, 'This is the assertion that fails; some properties of the object are stale');
}

1 个答案:

答案 0 :(得分:1)

这是因为尚未加载关系。

您可以尝试$contact->load('marketingOrigin');来渴望建立关系:

public function saveMarketingOriginInfo(Contact $contact, $data) {
    $contact->marketingOrigin()->create($data);        
    $this->makeOtherChangesByReference($contact->marketingOrigin);
    $contact->marketingOrigin->save();
    $contact->load('marketingOrigin'); // <---- eager load the relationship
    return $contact->marketingOrigin; 
}