我在Laravel 5.5
中构建了一个小应用程序,我在Interaction
模型中有两个模型:Interaction Summary
和Interaction
我&#39 ;我有以下关系:
public function meetingSummaries()
{
return $this->hasMany('App\InteractionSummary');
}
现在要在我的控制器中使用以下内容创建交互:
$data = $request->only('user_id', 'event_type', 'schedule', 'summaries', 'type', 'venue', 'with_client');
$data['schedule'] = Carbon::parse($request->schedule)->addHours(5)->addMinutes(30)->toDateTimeString();
$meeting = [];
$meeting['user_id']= $data['user_id'];
$meeting['schedule'] = $data['schedule'];
$meeting['type'] = $data['type'];
$meeting['with_client'] = $data['with_client'];
$meeting['venue'] = $data['venue'];
$meeting['event_type'] = $data['event_type'];
$interaction = Interaction::create($meeting);
if($data['summaries'])
{
$container = [];
foreach($data['summaries'] as $summary)
{
$summary = (Object)$summary;
if($summary->client['label'])
{
$container[] = new InteractionSummary([
'company_id' => $summary->client['label'],
'nature' => $summary->type,
'user_id' => $summary->mention['label'],
'action' => $summary->action,
'feedback' => $summary->comment
]);
}
}
}
$interaction->meetingSummaries()->saveMany($container);
}
但是在更新时我并不知道要克服这个问题,因为在我的字段中可能会有新的或旧的关系数据。我正在尝试这样的事情:
if($data['summaries'])
{
$container = [];
foreach($data['summaries'] as $summary)
{
$summary = (Object)$summary;
if($summary->id)
{
$container[] = new InteractionSummary([
'id' => $summary->id,
'company_id' => $summary->client['value'],
'nature' => $summary->type,
'user_id' => $summary->mention['value'],
'action' => $summary->action,
'feedback' => $summary->comment
]);
}
else {
$container[] = new InteractionSummary([
'company_id' => $summary->client['value'],
'nature' => $summary->type,
'user_id' => $summary->mention['value'],
'action' => $summary->action,
'feedback' => $summary->comment
]);
}
}
$interaction->meetingSummaries()->save($container);
}
哪个寄给我错误:
类型错误:传递给Illuminate \ Database \ Eloquent \ Relations \ HasOneOrMany :: save()的参数1必须是Illuminate \ Database \ Eloquent \ Model的实例,给定数组,在〜\ app \ Http \ Controllers \中调用第449行的InteractionsController.php
如果我这样做:
$interaction->meetingSummaries()->saveMany($container);
我重复了新的领域。
指导我如何克服这一点。感谢。
答案 0 :(得分:2)
使用findOrNew()
方法:
$summaryItem = InteractionSummary::findOrNew($summary->id);
$summaryItem->fill([
'company_id' => $summary->client['value'],
'nature' => $summary->type,
'user_id' => $summary->mention['value'],
'action' => $summary->action,
'feedback' => $summary->comment
]);