как исправить: SQLSTATE [23000]: нарушение ограничения целостности: 1452 Невозможно добавить или обновить дочернюю строку: ограничение внешнего ключа не выполнено - PullRequest
0 голосов
/ 17 октября 2019

как я могу исправить эту ошибку?

это моя ошибка:

SQLSTATE [23000]: нарушение ограничения целостности: 1452 Невозможно добавить или обновить дочернюю строку: чужаяСбой ключевого ограничения (coachers. article_comments, CONSTRAINT article_comments_user_id_foreign FOREIGN KEY (user_id) ССЫЛКИ users (id)) (SQL: вставить в article_comments (name, email,description, article_id, user_id, updated_at, created_at) значения (aaaaa, aaa@gmail.com, hhhhhhsssshhshsh, 1, 0, 2019-10-17 08:12:17, 2019-10-17 08:12:17))

 public function commentArticle($user_id, $article_id, Request $request)
    {

        if (!$user_id == 0) {
            $register = $request->validate([
                'description' => 'required|min:5',
            ]);
            $commentarticle = new articleComment();
            $commentarticle->description = $request->input('description');
            $commentarticle->user_id = $user_id;
            $commentarticle->article_id = $article_id;
            $commentarticle->name = 'name';
            $commentarticle->email = 'email';
            $commentarticle->submit = 0;
            $commentarticle->save();
            return $request;

        }
        else if ($user_id == 0) {
            $register = $request->validate([
                'description' => 'required|min:5',
                'name' => 'required|min:3',
                'email' => 'required|min:5|max:150|email',
            ]);
            $comment = new articleComment();
            $comment->name = $request->input('name');
            $comment->email = $request->input('email');
            $comment->description = $request->input('description');
            $comment->article_id = $article_id;
            $comment->user_id = 0;
            $comment->save();
            return $comment;
        }
    }

и мой API:

Route::post('comment-article/{user_id}/{article_id}', 'ArticleController@commentArticle');

и мой стол

public function up()
    {
        Schema::create('article_comments', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedInteger('user_id')->unique()->nullable();
            $table->foreign('user_id')->references('id')->on('users');
            $table->unsignedInteger('article_id')->unique()->nullable();
            $table->foreign('article_id')->references('id')->on('articles');
            $table->string('name')->nullable();
            $table->string('email')->nullable();
            $table->string('submit')->nullable();
            $table->string('description')->nullable();
            $table->timestamps();
        });
    }

Ответы [ 2 ]

1 голос
/ 17 октября 2019

удалить unique() метод из столбцов user_id и article_id и снова запустить миграцию ..

public function up()
    {
        Schema::create('article_comments', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedInteger('user_id')->nullable();
            $table->foreign('user_id')->references('id')->on('users');
            $table->unsignedInteger('article_id')->nullable();
            $table->foreign('article_id')->references('id')->on('articles');
            $table->string('name')->nullable();
            $table->string('email')->nullable();
            $table->string('submit')->nullable();
            $table->string('description')->nullable();
            $table->timestamps();
        });
    }

, если user_id нет, тогда user_id установить ноль не (ноль) 0

$comment->user_id = NULL;
1 голос
/ 17 октября 2019

Похоже, что в вашей таблице users нет пользователя с id == 0. А поскольку существует ограничение внешнего ключа, операция завершается неудачей.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...