为什么有两个输入发送到数据库而不是一个?

时间:2019-05-12 15:02:43

标签: php laravel debugging

我只是不知道这是怎么发生的。用户输入文本后,它将文本的两个副本发送到数据库,而不是一个。我很确定我的代码是正确的,但是不确定为什么它会在数据库中发送用户输入的重复副本。

我在做什么错了?

enter image description here

这是我的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));
    }
}

1 个答案:

答案 0 :(得分:0)

实际上,我不会在您的代码中投入太多,但是您可以

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

您可以尝试文档中介绍的各种createinsert方法。

我也不认为每次插入都检索用户的所有帖子都是您使用$request->user()->posts()所做的好习惯。