【问题标题】:Laravel 5.2: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails, without using a laravelcollectiveLaravel 5.2:完整性约束违规:1452 无法添加或更新子行:外键约束失败,不使用 laravelcollective
【发布时间】:2017-10-09 05:56:22
【问题描述】:

我有一个简单的组模型和一个联系人模型。

Contact "belongsTo" 一个 Group 和 Group "hasMany" Contact。

因此我的文章迁移有一个名为“user_id”的外键。

*Group.php*
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Group extends Model
{
    public function contacts()
    {
        return $this->hasMany('App\Contact', 'group_id');
    }
}

Contact.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    protected $fillable = ['name', 'company', 'email', 'phone', 'address', 'group_id'];

    public function group()
    {
        return $this->belongsTo('App\Group', 'group_id');
    }
}

*ContactsController.php*
public function create()
{
    // return 'Create New Contact';
    $groups = Group::all();

    return view('contacts.create', ['groups' => $groups]);

}

【问题讨论】:

  • 因此我的文章迁移有一个名为“group_id”的外键 * 错误抱歉!
  • 清空具有外键的数据库表,然后运行迁移
  • 运行迁移时会出现“[Symfony\Component\Debug\Exception\FatalThrowableError] Class 'CreateGroupsTable' not found”
  • ` public function up() { Schema::create('contacts', function (Blueprint $table) { $table->increments('id'); $table->integer('group_id ')->unsigned()->default(0); $table->foreign('group_id')->references('id')->on('groups')->onDelete('cascade'); $ table->string('name'); $table->string('company'); $table->string('email'); $table->string('phone'); $table->string('地址'); $table->timestamps(); }); `

标签: php mysql laravel laravel-5.2


【解决方案1】:

尝试以下方法:

  1. 从数据库中删除所有表
  2. 运行composer dump-autoload
  3. 检查所有迁移文件是否具有正确的文件名、类名和日期前缀(见下文)
  4. 运行php artisan migrate

迁移:

类名必须与文件名一致

例如:在文件“2014_12_08_100923_create_items_tables.php”中,必须是名称为“CreateItemsTables”且使用驼峰式单词的类。

文件名必须遵循正确的日期前缀格式

迁移文件必须命名为 YYYY_MM_DD_000000_create_some_table.php

【讨论】:

  • 我已经完成了这些步骤,发现其中一个表的名称有错误,但在输入新联系人时它给了我同样的错误。我为 Datebase Seeder.php 使用虚拟数据。In ContactsControlle ->public function create() { // return 'Create New Contact'; $groups = 组::all();返回视图('contacts.create', ['groups' => $groups]); }
猜你喜欢
  • 2016-10-27
  • 2020-08-13
  • 1970-01-01
  • 2014-03-12
  • 2015-05-25
  • 1970-01-01
  • 2014-01-09
相关资源
最近更新 更多