【发布时间】:2018-12-10 11:03:26
【问题描述】:
我正在使用 Laravel 5.7,并且在两个 eloquent 模型之间有一个 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' 作为主键。)
我做错了什么?
如何在不进行数据库读取查询 (find()) 的情况下返回刚刚保存在上一行 ($contact->marketingOrigin->save();) 中的相同对象?
更新以响应 cmets:
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');
}
【问题讨论】:
-
请发
marketingOrigin关系和测试。 -
@JonasStaudenmeir 我按照你的要求添加了关系和测试。谢谢。
标签: laravel laravel-5 eloquent