2013-12-20 2 views
7

이 질문은 이미 받았지만 아직도 내가하는 일을 찾을 수 없습니다. 잘못된.SQLSTATE [23000] : 무결성 제약 조건 위반 : 1452 자식 행을 추가하거나 업데이트 할 수 없습니다. 외래 키 제약 조건이 적용되지 않습니다. - Laravel

프레임 워크 Laravel을 사용하고 있습니다.

2 개의 테이블 (사용자 및 위치)이 있습니다.

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (festival_aid . users , CONSTRAINT fk_users_locations1 FOREIGN KEY (location_id) REFERENCES locations (location_id) ON DELETE CASCADE ON UPDATE NO ACTION) (SQL: insert into users (user_id , user_email , location_id) values (?, ?, ?)) (Bindings: array (0 => '1', 1 => '[email protected]', 2 => '1',))

표 사용자

CREATE TABLE IF NOT EXISTS `festival_aid`.`users` (
    `user_id` BIGINT NOT NULL AUTO_INCREMENT, 
    `user_email` VARCHAR(45) NOT NULL, 
    `user_created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, 
    `user_modified` TIMESTAMP NULL, 
    `user_deleted` TIMESTAMP NULL, 
    `user_lastlogin` TIMESTAMP NULL, 
    `user_locked` TIMESTAMP NULL, 
    `location_id` BIGINT NOT NULL, 
    PRIMARY KEY (`user_id`), 
    UNIQUE INDEX `user_email_UNIQUE` (`user_email` ASC), 
    CONSTRAINT `fk_users_locations1` 
    FOREIGN KEY (`location_id`) 
    REFERENCES `festival_aid`.`locations` (`location_id`) 
    ON DELETE CASCADE 
    ON UPDATE NO ACTION, 
ENGINE = InnoDB; 

테이블 위치

DROP TABLE IF EXISTS `festival_aid`.`locations` ; 

CREATE TABLE IF NOT EXISTS `festival_aid`.`locations` (
    `location_id` BIGINT NOT NULL AUTO_INCREMENT, 
    `location_latitude` FLOAT NOT NULL, 
    `location_longitude` FLOAT NOT NULL, 
    `location_desc` VARCHAR(255) NULL, 
    `location_type` VARCHAR(45) NULL, 
    PRIMARY KEY (`location_id`)) 
ENGINE = InnoDB; 

마이그레이션 사용자

public function up() 
    { 
     Schema::table('users', function(Blueprint $table) 
     { 
      $table->increments('user_id'); 
      $table->string('user_email'); 
      $table->timestamp('user_created'); 
      $table->timestamp('user_modified'); 
      $table->timestamp('user_deleted'); 
      $table->timestamp('user_lastlogin'); 
      $table->timestamp('user_locked'); 

      $table->foreign('location_id') 
       ->references('id')->on('locations'); 
      //->onDelete('cascade'); 
     }); 
    } 

마이그레이션 위치 : 사용자를 생성 할 때, 나는 오류 메시지가

public function up() 
    { 
     Schema::table('locations', function(Blueprint $table) 
     { 
      $table->primary('location_id'); 
      $table->float('location_latitude'); 
      $table->float('location_longitude'); 
      $table->string('location_desc'); 
      $table->string('location_type'); 
     }); 
    } 

모델 사용자

public function location() 
    { 
     return $this->belongsTo('Location'); 
    } 

모델 위치

public function store() 
    { 
     $input = Input::all(); 

     $rules = array('user_email' => 'required|unique:users|email'); 

     $v = Validator::make($input, $rules); 

     if($v->passes()) 
     { 
      $user = new User(); 
      $location = new Location(); 

      $user->user_email = $input['user_email']; 
      //$user->location_id = $input['location_id']; 

      $location->location_latitude = $input['location_latitude']; 
      $location->location_longitude = $input['location_longitude']; 

      $user->save(); 
      $location->save(); 
    } 

나는 내가 잘못 찾을 수없는 것

public function user() 
    { 
     return $this->hasOne('User'); 
    } 

컨트롤러. 분명히 외래 키에 문제가 있습니다.

답변

11

사용자 행에 유효한 위치에 대한 참조가 필요합니다. 사용자를 저장하기 전에 해당 위치를 사용할 수 있어야합니다. 그래서 먼저 위치를 저장 한 다음 사용자를 저장하고 $user->location_id 행의 주석 처리를 제거하면 작업이 완료된 것입니다. 이 오류에 직면

+7

이상하지만 내 경우에는 삽입하기 전에 제약 조건 테이블에 행이 있지만 여전히이 오류가 발생합니다. –

0

그 개발자 :

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row:
a foreign key constraint fails (laravel . articles , CONSTRAINT articles_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE)
(SQL: insert into articles (title , user_id , body , updated_at , created_at) values (rao, 1, sflkkjk, 2016-03-01 20:45:32, 2016-03-01 20:45:32))
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row:
a foreign key constraint fails (laravel . articles , CONSTRAINT articles_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE)
(SQL: insert into articles (title , user_id , body , updated_at , created_at) values (rao, 1, sflkkjk, 2016-03-01 20:45:32, 2016-03-01 20:45:32))

먼저 저장 한 사용자의 사용자 레코드는 다음 쉽게 데이터베이스에 삽입 레코드를 삽입하려고합니다.

주요 포인트

두 테이블 : 하나는 기사이며, 사용자가 다른 것입니다. 사용자는 기사가 많지만 기사가 많지 않습니다. 따라서 외래 키가 상품 테이블쪽으로 이동합니다. 사용자 테이블에 레코드가 없으면 앞에서 설명한 것과 같은 오류가 발생합니다.

이렇게하면 쉽게이 문제를 해결할 수 있습니다.

관련 문제