![](/img/trans.png)
[英]inserting data into database laravel 5.6 relation belongstomany pivot table
[英]Storing data in database pivot table Laravel
我有兩個多對多關系的表,由下表連接
我在我的控制器中使用下面的 store 方法,但是當調用它時返回一個錯誤:完整性約束違規:1048 列 'thought_journal_entry_id' 不能為空(SQL:插入到thought_journal_entry_emotions
( emotion_id
, thought_journal_entry_id
)值(1 thought_journal_entry_id
))
我知道thought_journal_entry_id
沒有 id,但我不確定如何找到它。 嘗試$entry = ThoughtJournalEntry::find(1)
它可以工作,但我需要為 ThoughtJournalEntry $entry = new ThoughtJournalEntry
新實例存儲數據 我該怎么做?
public function store(Request $request)
{
$this->validate($request, [
'thought_entry' => 'required'
]);
$entry = new ThoughtJournalEntry;
$entry->user_id = auth()->user()->id;
$entry['entry_date'] = date('Y-m-d H:i');
$entry->thought = $request->input('thought_entry');
$emotions = $request->has('emotions') ? $request->get('emotions') : [];
$emotions2 = Emotions::find($emotions);
$entry->emotions()->sync($emotions2);
$entry->tt_id = $request->has('thinking_traps') ? $request->get('thinking_traps') : [];
$entry->balanced_thought = $request->input('balanced_thought');
$entry->save();
return redirect('/dashboard');
}
您需要先保存ThoughtJournalEntry $entry
模型以獲取 id。 然后將情緒同步到入口
public function store(Request $request)
{
$this->validate($request, [
'thought_entry' => 'required'
]);
$entry = new ThoughtJournalEntry;
$entry->user_id = auth()->user()->id;
$entry['entry_date'] = date('Y-m-d H:i');
$entry->thought = $request->input('thought_entry');
$emotions = $request->has('emotions') ? $request->get('emotions') : [];
$entry->tt_id = $request->has('thinking_traps') ? $request->get('thinking_traps') : [];
$entry->balanced_thought = $request->input('balanced_thought');
$entry->save();
$emotions2 = Emotions::find($emotions);
$entry->emotions()->sync($emotions2);
return redirect('/dashboard');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.