首页 > 解决方案 > 为什么有两个输入被发送到数据库而不是一个?

问题描述

我只是不明白这是怎么回事。当用户输入文本时,它的两个副本被发送到数据库而不是一个。我很确定我的代码是正确的,但不确定为什么它会在数据库中发送用户输入的重复副本。

我究竟做错了什么?

在此处输入图像描述

这是我create_posts_table在迁移文件夹中的:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('body', 140);
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

发布到数据库:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;

class PostController extends Controller
{
    public function create(Request $request, Post $post) {
        // create post
        $createdPost = $request->user()->posts()->create([
            'body' => $request->body
        ]);

        // return response
        return response()->json($post->with('user')->find($createdPost->id));
    }
}

标签: phplaraveldebugging

解决方案


实际上,我并没有过多介绍您的代码,但是您可以

$post = App\Post::firstOrCreate(['body' => 'body' => $request->body]);

您可以尝试文档中描述的各种创建插入方法。

此外,我不认为为每个插入检索用户的所有帖子是一个好习惯,你正在使用$request->user()->posts().


推荐阅读