php - 插入数据mysql数据库时出错,

标签 php mysql sql laravel-5 foreign-key-relationship

在将数据插入 mysql 数据库时,我收到下面的错误,并且根据之前关于 stackoverflow 的一些问题的答案,我将 protected $fillable 放在我的模型文件中但仍然显示错误。

当我创建我的第一个条目表时它接受没有任何错误但是当我创建我的新条目时它显示错误。

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`app`.`articles`, CONSTRAINT `articles_ibfk_1` FOREIGN KEY (`article_id`) REFERENCES `users` (`id`)) (SQL: insert into `articles` (`article_head`, `article_body`) values (abkskfbasfbv, zbfvaksdvaskdvjsdc
))

文章.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
  protected $fillable = [
      'article_head', 'article_body',
  ];
    public $timestamps = false;
}

迁移文件

<?php

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

class CreateArticlesTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('articles', function(Blueprint $table)
        {
            $table->increments('article_id');
            $table->string('article_head', 500);
            $table->string('article_body', 10000);
            $table->dateTime('created_on');
            $table->timestamps();
        });
    }


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

}

2016_04_27_181606_add_foreign_keys_to_articles_table.php

<?php

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

class AddForeignKeysToArticlesTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('articles', function(Blueprint $table)
        {
            $table->foreign('article_id', 'articles_ibfk_1')->references('id')->on('users')->onUpdate('RESTRICT')->onDelete('RESTRICT');
        });
    }


    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('articles', function(Blueprint $table)
        {
            $table->dropForeign('articles_ibfk_1');
        });
    }

}

最佳答案

protected $primaryKey = "article_id"; 

在您的文章模型中。

关于php - 插入数据mysql数据库时出错,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36920518/

相关文章:

javascript - 模板在正确加载之前中断

php - 如何插入多行,每行都有一个数组?

mysql - 无法访问 phpmyadmin - Ubuntu MySQL

mysql - SQL:如果同一个表中没有其他具有特殊不同值的条目,则只显示条目

javascript - 如何将参数 lang 传递给另一个 url

php - mysql插入记录

php - 带有签名 URL 的 Google Storage REST PUT

mysql - 无法获得我想要的 View : MySQL

mysql - 如何编写 SQL 查询以将两个表与映射表连接起来并获得每个结果只有一行的格式化输出?

java - 为什么字符串打印不正确?