laravel 链接数据库表

问题描述 投票:0回答:1

我正在制作一个向帖子添加评论的功能。我可以创建评论并将其保存到数据库中,但我正在努力处理数据库关系。

我有一个功能

addComment
,它将评论保存到
comment
表中,这很好。但是我不知道如何将帖子的ID和刚刚创建的评论添加到我的
postscomments 
表中。

我想在函数中添加这样的东西:

    $post_id = Posts::where('id', $currentPost);

    $postComment = new PostsComments();
    $postComment->post_id = $post_id;
    $postComment->comment_id = $comment->id
    $postComment->save();

但我很确定这不是将表格相互链接的正确方法。

如何将这些表相互链接?然后在链接时从数据库中获取值?

我将数据添加到数据库的功能:

public function addComment(Request $request, String $id)
    {
        $validator = Validator::make($request->all(), [
            'comment' => ['required'],
        ]);

        $comment = new Comments();
        $comment->comment = $request->comment;
        $comment->save();

        $response = [
            'id' => $comment->id
        ];

        if ($validator->fails()) {
            return response()->json($response);
        }

        return response()->json($response);
    }

我的评论后迁移:

  public function up()
    {
        Schema::create('posts_comments', function (Blueprint $table) {
            $table->id();
            $table->integer('post_id');
            $table->integer('comment_id');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('posts_comments');
    }

我的帖子迁移:

  public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->integer('user_id');
            $table->string('title');
            $table->string('description');
        });
    }

我的评论迁移:

  public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->id();
            $table->string('comment');
            $table->timestamps();
        });
    }

我的数据库模型:

php laravel database relationship
1个回答
1
投票

正如我在评论中所解释的,我认为你的桌子应该是

  • 用户(id,...)
  • posts (id, user_id, title, description)
  • 评论(id、user_id、post_id、正文)
                               +---------+
                               | users   |
                             1 +---------+
+------------------------------| id (pk) |---------------------------------+
|                              +---------+                                 |
|                                                                          |
|     +--------------+                                +--------------+     |
|     | posts        |                                | comments     |     |
|     +--------------+ 1                              +--------------+     |
| *   | id (pk)      |---------------+                | id (pk)      |   N |
+--->>| user_id (fk) |               |            N   | user_id (fk) |<<---+
      | title        |               +-------------->>| post_id (fk) |
      | description  |                                | comment      |
      +--------------+                                +--------------+

至于如何将表链接在一起,您应该在迁移文件中声明外键约束。

// posts migration
$table->id();
$table->foreignId('user_id')->constrained('users');
$table->string('title');
$table->string('description'); // consider using text('description') instead if it's going to be large
// comments migration
$table->id();
$table->foreignId('user_id')->constrained('users');
$table->foreignId('post_id')->constrained('posts');
$table->string('comment'); // consider using text('comment') instead if it's going to be large

然后你需要定义模型之间的关系

// User model
public function posts()
{
    return $this->hasMany(Post::class);
}

public function comments()
{
    return $this->hasMany(Comment::class);
}
// Post model
public function user()
{
    return $this->belongsTo(User::class);
}

public function comments()
{
    return $this->hasMany(Comment::class);
}
// Comment model
public function user()
{
    return $this->belongsTo(User::class);
}

public function post()
{
    return $this->belongsTo(Post::class);
}

至于如何在添加评论时链接你的模型,你可以这样定义一个路由:

Route::post('/posts/{post}/comments', [PostCommentsController::class, 'store'])->name('posts.comments.store');
class PostCommentsController extends Controller
{
    public function store(Request $request, Post $post)
    {
        $validated = $request->validate([
            'comment' => ['required'],
        ]);

        $comment = $post->comments()->create($validated + ['user_id' => Auth::user()]);

        return response()->json(['id' => $comment->id], 201);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.