我有 2 個表格,我想用一個表格發布并同時創建評論。我怎樣才能在 Laravel 中做到這一點?
帖子表
| ID | 標題 | 蛞蝓 |
|---|---|---|
| 1 | 你好世界 | 你好世界 |
| 2 | 哦嗨 | 哦嗨 |
評論表
| ID | post_id | 身體 |
|---|---|---|
| 1 | 1 | Lorem ipsum |
| 2 | 2 | Lorem ipsum |
| 3 | 2 | Lorem ipsum 第二個相同的帖子 |
uj5u.com熱心網友回復:
我假設您的表單看起來像帖子標題輸入和帖子內容輸入。
因此,在您的控制器中,當您收到包含表單值的請求時,您可以執行以下操作:
$title = $request->title;
$body = $request->body;
// This line will only work if you imported your Eloquent model (use App\Models\Posts as an example)
$post = new Post;
$post->body = $body;
// For the slug just manipulate the string in order to have the desired output and do the same
$post->slug = $slug;
$post->save();
// Now get the id
$post_id = $post->id;
$comment = new Comment;
$comment->post_id = $post_id;
$comment->body = $body;
$comment->save();
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/422696.html
標籤:
