【问题标题】:error while inserting data mysql database,插入数据mysql数据库时出错,
【发布时间】:2016-08-23 13:30:50
【问题描述】:

在将数据插入 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');
        });
    }

}

【问题讨论】:

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


【解决方案1】:

protected $primaryKey = "article_id"; 

在您的文章模型中。

【讨论】:

  • 不,它不起作用,当我在文章表中创建第一个条目时,它没有任何错误地接受,但是当我制作新条目时,它显示错误
【解决方案2】:

这只是意味着您插入的表格文章上的 article_id 值在表格用户上不存在,或者您没有为表格用户的文章插入值。请记住,表 users 上列 article_id 的值取决于表 users 上 ID 的值

【讨论】:

  • 我是否将 id 列添加到我的文章表中
  • 是的,试试看!
  • 那么列类型的某些字段肯定有问题
  • 当我在文章表中创建第一个条目时,它没有任何错误地接受,但是当我创建新条目时,它显示错误
  • {完整性约束违规:1452 无法添加或更新子行:外键约束失败(app.articles,CONSTRAINT articles_ibfk_1 FOREIGN KEY(id)参考@987654325 @ (id))}
猜你喜欢
  • 1970-01-01
  • 2013-04-25
  • 2014-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-04
  • 1970-01-01
相关资源
最近更新 更多