发帖时从另一个 table 获取正文
Getting body from another table while posting
我有 2 个 table 我想 post 使用单个表单并同时创建评论。我如何在 Laravel 中执行此操作?
帖子table
id
title
slug
1
Hello world
hello-world
2
O hi
o-hi
评论table
id
post_id
body
1
1
Lorem ipsum
2
2
Lorem ipsum
3
2
Lorem ipsum second same post
我假设您的表单看起来像 post 标题输入和 post 内容输入。
因此,在您的控制器中,当您收到包含表单值的请求时,您可以执行以下操作:
$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();
我有 2 个 table 我想 post 使用单个表单并同时创建评论。我如何在 Laravel 中执行此操作?
帖子table
id | title | slug |
---|---|---|
1 | Hello world | hello-world |
2 | O hi | o-hi |
评论table
id | post_id | body |
---|---|---|
1 | 1 | Lorem ipsum |
2 | 2 | Lorem ipsum |
3 | 2 | Lorem ipsum second same post |
我假设您的表单看起来像 post 标题输入和 post 内容输入。
因此,在您的控制器中,当您收到包含表单值的请求时,您可以执行以下操作:
$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();