Laravel/MariaDB: 错误号 150 "Foreign key constraint is incorrectly formed"

Laravel/MariaDB: errno 150 "Foreign key constraint is incorrectly formed"

我正在使用 Laravel 5.4、PHP 5.6、Ubuntu 18.04、MariaDB 10.4.8。当我 运行 php artisan migrate 时,我得到:

In Connection.php line 647:
                                                                                                                     
  SQLSTATE[HY000]: General error: 1005 Can't create table `test-kursach-backend`.`comments` (errno: 150 "Foreign ke  
  y constraint is incorrectly formed") (SQL: alter table `comments` add constraint `comments_post_id_foreign` forei  
  gn key (`post_id`) references `posts` (`id`))                                                                      
                                                                                                                     

In Connection.php line 449:
                                                                                                                     
  SQLSTATE[HY000]: General error: 1005 Can't create table `test-kursach-backend`.`comments` (errno: 150 "Foreign ke  
  y constraint is incorrectly formed")

我正在尝试使用 https://github.com/klisl/laravel-comments。在尝试使用此包执行迁移之前,我在 phpMyAdmin 中创建了数据库,通过添加数据库名称和内容配置了 .env,成功地 运行 php artisan migratephp artisan make:authphp artisan make:controller AuthController。然后,在 运行ning php artisan vendor:publish --provider="Klisl\Comments\CommentsServiceProvider" 之后,我在 migrations 文件夹中得到 2 个新文件:date_number_CreateCommentsTable.phpdate_number_ChangeCommentsTable.php

以下是这 2 个文件的来源:

CreateCommentsTable.php:

<?php

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

/**
 * Class CreateCommentsTable
 */
class CreateCommentsTable extends Migration
{

    /** @return void */
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email');
            $table->text('text');
            $table->integer('parent_id')->nullable(); //разрешаем null; 
            $table->boolean('status')->default(config('comments.show_immediately')); 
            $table->timestamps();
        });
    }

    /** @return void */
    public function down()
    {
        Schema::dropIfExists('comments');
    }

}

ChangeCommentsTable.php:

<?php

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

/**
 * Class ChangeCommentsTable
 */
class ChangeCommentsTable extends Migration
{

    /** @return void */
    public function up()
    {
        Schema::table('comments', function (Blueprint $table) { 
            $table->integer(config('comments.key_field'))->unsigned();      
            $table->foreign(config('comments.key_field'))->references('id')->on(config('comments.key_table'));  
            
            if(config('comments.user')){
                $table->integer('user_id')->unsigned()->nullable(); //разрешаем null        
                $table->foreign('user_id')->references('id')->on('users');
            }
        });
    }

    /** @return void */
    public function down()
    {
        Schema::table('comments', function (Blueprint $table) {
            //
        });
    }

}

然后我 运行 php artisan migrate 得到了我在上面写的错误。

我已经尝试在 CreateCommentsTable 中添加 ->unsigned()。我还尝试将外键从 ChangeCommentsTable 的函数中移除,如下所示:

    /** @return void */
    public function up()
    {
        Schema::table('comments', function (Blueprint $table) { 
            $table->integer(config('comments.key_field'))->unsigned();          
            
            if(config('comments.user')){
                $table->integer('user_id')->unsigned()->nullable(); //разрешаем null        
            }
        });

        Schema::table('comments', function ($table){
           $table->foreign(config('comments.key_field'))->references('id')->on(config('comments.key_table'));
        });
        Schema::table('comments', function ($table){
            if(config('comments.user')){
                $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            }
        });
    }

    /** @return void */
    public function down()
    {
        Schema::dropForeign([config('comments.key_field')]);
        Schema::dropForeign(['user_id']);
        Schema::table('comments', function (Blueprint $table) {
            //
        });
    }

还有这个:

Schema::table('comments', function ($table){
   $table->foreign(config('comments.key_field'))->references('id')->on(config('comments.key_table'));
    if(config('comments.user')){
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    }
});

由于任何一个都没有解决,我决定 post 上面的源代码的默认版本。如果你能帮我解决这个问题,你真的可以拯救我的一天 c:

UPD:这是来自 CommentController.php 的来源:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;
use Auth;
use App\Comment;
use App\Post;


class CommentController extends Controller
{

    /**
     * Processing form - AJAX
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {

        $data = $request->except('_token', 'comment_post_ID', 'comment_parent');
        
        //adding  fields with same names like in table (models)
        $data['post_id'] = $request->input('comment_post_ID');
        $data['parent_id'] = $request->input('comment_parent');
        
        $data['status'] = config('comments.show_immediately');


        $user = Auth::user();

        if($user) {
            $data['user_id'] = $user->id;
            $data['name'] = (!empty($data['name'])) ? $data['name'] : $user->name;
            $data['email'] = (!empty($data['email'])) ? $data['email'] : $user->email;                              
        }

        $validator = Validator::make($data,[
            'post_id' => 'integer|required',
            'text' => 'required',
            'name' => 'required',
            'email' => 'required|email',
        ]);

        $comment = new Comment($data); 


        if ($validator->fails()) {
            return response()->json(['error'=>$validator->errors()->all()]);
        }
        

        $post = Post::find($data['post_id']);

        $post->comments()->save($comment);
        

        $data['id'] = $comment->id;
        $data['hash'] = md5($data['email']);
        $data['status'] = config('comments.show_immediately');
        

        $view_comment = view(env('THEME').'.comments.new_comment')->with('data', $data)->render();

        return response()->json(['success'=>true, 'comment'=>$view_comment, 'data'=>$data]);

    }
}

评论中缺少外键table,试试看:

Schema::create('comments', function (Blueprint $table) {
 $table->integer('post_id')->unsigned();      
 $table->foreign('post_id')->references('id')->on('posts')

我不确定如何在 laravel 5.4 中添加外键让我知道这是否有效。

我还没有帖子table所以问题通过添加解决了。我会尽可能将此答案标记为正确。