2012-09-14 44 views
0

添加新的記錄它給出了一個錯誤:Yii中增加新的記錄錯誤:1452無法添加或更新子行,外鍵約束失敗

1452 Cannot add or update a child row: a foreign key constraint fails

public function relations() 
{ 
    return array(
     'data' => array(self::HAS_ONE, 'Data', 'id'), 
    ); 
} 

這裏是我添加一個新的代碼記錄:

public function actionAdd_Record() 
{ 
    $users = new Users(); 
    $data = new Data(); 


    if (isset($_POST['Users']) && isset($_POST['Data'])) { 

     if(!empty($_POST['Users_password'])) $_POST['Users']['password']=md5($_POST['Users_password']); 
     $users->created_date=date('Y-m-d H:i:s'); 


     CActiveForm::validate(array($users, $data)); 
     $users->attributes = $_POST['Users']; 
     $data->attributes = $_POST['Data']; 

     $valid=$users->validate(); 
     $valid=$data->validate() && $valid; 


     if($valid){ 
      $users->save(); 
      $data->save(); 

      $this->redirect(
       array('view_record', 
        'id'=> $users->id) 
      ); 
     } 
    } 

    $this->render(
     'add_record', array(
      'users'=> $users, 
      'data'=>$data 
     ) 
    ); 
} 

這是第一個表:

CREATE TABLE IF NOT EXISTS `data` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `investment_amount` float DEFAULT '0' COMMENT '投資額', 
    `withdrawals` float DEFAULT '0' COMMENT '引出額', 
    `investment_yield` float DEFAULT '0' COMMENT '運用利回り', 
    `account_balance` float DEFAULT '0' COMMENT '口座殘高', 
    `status_account` enum('open','closed') DEFAULT 'open', 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ; 

,第二個表:

CREATE TABLE IF NOT EXISTS `users` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `username` varchar(128) NOT NULL, 
    `password` varchar(128) NOT NULL, 
    `name` varchar(300) NOT NULL COMMENT '氏名', 
    `email` varchar(200) NOT NULL, 
    `user_type` enum('normal','admin') NOT NULL DEFAULT 'normal', 
    `created_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=9 ; 

,它給這個錯誤:

CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (money_investment . data , CONSTRAINT FK_data_users FOREIGN KEY (id) REFERENCES users (id)). The SQL statement executed was: INSERT INTO data (investment_amount , withdrawals , investment_yield , account_balance , status_account) VALUES (:yp0, :yp1, :yp2, :yp3, :yp4)

回答

1

感謝您的幫助,我固定我的問題。

我說$data->id=$users->id;,因爲第二個表還沒有收到有關的ID想法。見here

if($valid){ 
$users->save(); 
$data->id=$users->id; 
$data->save(); 


$this->redirect(
    array('view_record', 
     'id'=> $users->id) 
    ); 
} 
1

這不是警予或PHP的問題,而是一個數據庫的問題。

你試圖插入違反您已經定義的關係有關主鍵的記錄。需要檢查的是關係,以及領域的長度。

看起來你可能仍然在列定義的關係,不存在(money_investment?)

0

外鍵約束,不允許你在孩子進入數據父母.. 有時SQL引擎InnoDB和MyISAM的.. 讀出它的功能之前,你也會來了解SQL引擎將被優先使用根據外鍵約束的未來問題....

0

你切切實實的更新表。 最好的辦法是在型號

public function relations() 

到看到和比較你的表這些關係。 任何額外的或錯誤的關係都可能造成這樣的問題。

相關問題