Laravel - 外键不起作用的表 - 更新

时间:2017-05-31 15:30:31

标签: php laravel-5.2

我正在使用Laravel 5.2和MySQL。

我正在开发一个习惯Laravel的项目。我的项目是一个电话簿,您可以在桌面上存储联系信息。但要执行此操作,您需要使用make:auth命令登录系统。简单,似乎。

在我的“Users”表格中,我有字段ID。此表用于存储用户信息,以便他们可以登录和访问联系人。

在我存储联系人的“Contacts”表中,有一个名为“Created By”的列,该列应该从users表中获取字段ID,只是为了引用谁是所述联系人的创建者。

但事情就是这样:

联系人表格不会迁移,我的工作无关紧要。

我已经删除了两个表并从头开始创建USERS,因为它具有引用的主键,然后是CONTACTS,并设置了外部字段。我甚至放弃了我的模型并使用上面的相同顺序创建它们,因为谁知道什么可行。

以下是我的迁移文件:

USERS MIGRATION

----- ... -----

 public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email', 191)->unique();
            $table->string('password', 191);
            $table->timestamp('updated_at');
            $table->timestamp('created_at');
            $table->rememberToken();
        });
    }

----- ... -----

如上所述,该表具有我在其他表中引用的ID字段。

联系移民

----- ... -----

public function up()
    {
        Schema::create('contacts', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id', false, true);
            $table->foreign('user_id')->references('id')->on('users');
            $table->string('image');
            $table->string('name');
            $table->string('lastname');
            $table->string('email', 191)->unique();
            $table->string('phone',191)->unique();
            $table->string('address');
            $table->string('description', 255);
        });

----- ... -----

字段user_id引用表用户中的id字段,如上所述。第二个参数是设置递增为false,第三个参数是将unsigned设置为true。

即使我制作默认样式($ table->整数('user_id') - > unsigned(); --- $ table-> foreign .....;),迁移也不是'工作。

我甚至在这个主体的分离模式中创建了外来字段,如下所示:

Schema::table('contacts', function($table) {
            $table->foreign('user_id')->references('id')->on('users');
        });

但即使这样,迁移也无效。

我真的不知道发生了什么。

这是我的联系模式

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    // Getting the user associated with the contact
    // which means, I hope,
    // The user that created the contact entry in the table 'contacts'
    public function user()
    {
        return $this->belongsTo('App\User');
    }

    // protected $table = 'contacts';

    // not using an id field
    // could this be the error?
    // dunno
    // isn't laravel making an automatic id field?
    // dunno too
    public $fillable = array('name', 'lastname', 'email', 'phone', 'address');

    // public $foreign = ('user_id');

    //added because of error at migration
    public $timestamps = false; 


}

这是我的用户模型

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    // Putting it in simple terms
    // Hopefully, this will return
    // the many contacts that said user recorded in the 'contacts' table
    public function contact()
    {
        return $this->hasMany('App\Contact');
    }

    // protected $table = 'users';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

更新

我刚刚回滚了我的迁移并再次使用migrate命令,这次都有效。

我可以注册用户,因此auth::check可以正常工作,我可以看到带有表单的视图,以便在CONTACTS表格中插入联系人。

但是当我点击按钮保存时,我收到以下错误:

2/2

QueryException in Connection.php line 729:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`phonebook`.`contacts`, CONSTRAINT `contacts_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`))


1/2

PDOException in Connection.php line 457:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`phonebook`.`contacts`, CONSTRAINT `contacts_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`))

我仍然不知道发生了什么。

1 个答案:

答案 0 :(得分:1)

这些是您添加联系人和附加用户的一些方法。既然你解决了外键问题,我就不会解决这个问题了。

$user = \Auth::user();

$user->contact()->create([
    'name' => $request->input('name'),
    'lastname' => $request->input('lastname'),
    'email' => $request->input('email'),
    'phone' => $request->input('phone'),
    'address' => $request->input('address')
]);

或者

\App\Contact::create([
    'name' => $request->input('name'),
    'lastname' => $request->input('lastname'),
    'email' => $request->input('email'),
    'phone' => $request->input('phone'),
    'address' => $request->input('address'),
    'user_id' => \Auth::id()
]);

或者

$contact = new \App\Contact;

$contact->name = $request->input('name');
$contact->lastname = $request->input('lastname');
$contact->email = $request->input('email');
$contact->phone = $request->input('phone');
$contact->address = $request->input('address');
$contact->user_id = \Auth::id();

$contact->save();

当您批量指定值时,也会将user_id添加到$fillable属性中(上面显示的第二个选项)。