简体   繁体   中英

Laravel - Table with foreign key not working --Updated

I'm using Laravel 5.2 and MySQL.

I'm developing a project to get used to Laravel. My project is a phonebook, where you can store contact info on a table. But to do this, you need to be logged in the system, which I made using the make:auth command. Simplicity, it seems.

In my " Users " table I have the field ID . This table is used to store the user info so they can login and access the contact stuff.

In my " Contacts " table, which is where I store my contacts, is a column named " Created By " that is supposed to take the field ID from the users table, just to reference who was the creator of said contact.

But here is the thing:

The contacts table isn't migrating, it doesn't matter what I do.

I already dropped both tables and made them from scratch, the USERS first, because it has the referenced primary key, and then the CONTACTS , with the foreign field set. I even dropped my models and created them using the same order above, because who knows what might work.

Here is my migration files:

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();
        });
    }

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

As stated, the table has the ID field I am referencing in my other table.

CONTACTS MIGRATION

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

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);
        });

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

The field user_id references the id field in the table users, as stated. The second parameter is setting incrementing to false and the third is setting unsigned to true.

Even if I make the default style ($table->integer('user_id')->unsigned(); --- $table->foreign.....;), the migration isn't working.

I even made the foreign field in a separated schema from this main body, like so:

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

But even like this, the migration isn't working.

I really don't know what is happening.

This is my Contact Model

<?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; 


}

This is my User Model

<?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',
    ];
}

UPDATE

I just rolled back my migrations and use the migrate command again, and it worked this time.

I can register an user, so the auth::check works and I can see the view with the form to insert a contact in the CONTACTS table.

But when I click the button to save, I get the following error:

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`))

I still don't know what is going on.

These are some of the ways you can add a contact and attach the user. Since you solved the foreign key issue, i won't address that.

$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')
]);

Or

\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()
]);

Or

$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();

Also add user_id to the $fillable property when you mass assign the value (second option shown above).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM