coryj
coryj

Reputation: 1255

How can I link two tables in laravel?

I'm having an issue trying to link the user_id to another table using laravel. I'm using migrations, and can't seem to find what I'm doing wrong. I keep getting the error..

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child 
row: a foreign key constraint fails (`ship`.`units`, CONSTRAINT 
`units_user_id_foreign` FOREIGN KEY(`user_id`) REFERENCES `users` (`id`))

SQL: INSERT INTO `units` (`unit`, `updated_at`, `created_at`) VALUES (?, ?, ?)

Bindings: array (
  0 => 'i987',
  1 => '2012-11-27 19:19:42',
  2 => '2012-11-27 19:19:42',
)

Here is my migration..

Schema::create('users', function($table) {
    $table->increments('id');
    $table->string('email');
    $table->string('unit');
    $table->string('password');
    $table->timestamps();  
});
Schema::create('units', function($table) {
    $table->engine = 'InnoDB';
    $table->increments('id');
    $table->string('unit');
    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users');
    $table->timestamps();  
});

My User model...a user has one unit

return $this->has_one('Unit');

My Unit model...belongs to user

return $this->belongs_to('User');

For some reason, everytime I register a new user, it defaults the user_id in the unit table to 0. When I create a new user, I want the unit table to have the correct user_id so I can associate that user and unit. Can you see anything that I'm doing wrong here?

My User controller...

User::create(array(
  'email' => Input::get('email'),
  'password' => Hash::make($password)
  ));

  Unit::create(array(
    'unit' => Input::get('unit');
  ));

Upvotes: 0

Views: 3336

Answers (1)

mogetutu
mogetutu

Reputation: 508

In your Migration schema for units set the foreign key as

//Unit Schema Migration
$table->integer('user_id');

//User Controller
$unit = new Unit( array('unit' => Input::get('unit')));
$user = User::create(array(
                      'email' => Input::get('email'),
                      'password'=>Hash::make($password)
                     ));

$unit = $user->unit()->insert($unit);

Upvotes: 3

Related Questions