簡體   English   中英

MySQL完整性約束違規:1452

[英]MySQL Integrity constraint violation: 1452

我收到一個錯誤消息,告訴我表sales中不存在表fundssale_id列的值。 該值是通過獲取上一個sql查詢的LAST_INSERT_ID派生的。 每個查詢都存在於不同類的不同實例中。 注釋的代碼如下:

//this method which runs the first query belongs to this class
class sales {

    public  $sale_id,
            $acc_id,
            $sale_amt,
            $sale_date;



    public function create() {
        $db = database::instance()->connect();
        $sql = "INSERT INTO sales (sale_id,acc_id,sale_amt,sale_date) VALUES (DEFAULT, :acc_id, :sale_amt, :sale_date)";            
        $query = $db->prepare($sql);      
        $query->execute(array(
            ':acc_id' => $this->acc_id,
            ':sale_amt' => $this->sale_amt,
            ':sale_date' => $this->sale_date)
        );
        $perc = (Get('accounts','acc_perc','acc_id',$this->acc_id)); $perc = $perc[0];


        //create an instance of another class, "funds"
        $fund = new funds;
            $fund->acc_id = $this->acc_id;      
            $fund->fund_amt_total = $perc * $this->sale_amt;
            $fund->fund_date = $this->sale_date;


        //call a method of the class "funds"
        $fund->create();
    }           
}

第二個類,運行第二個查詢

class funds {

    public  $fund_id,
            $acc_id,
            $sale_id,
            $fund_amt,
            $fund_date;

    public function create() {
        $db = database::instance()->connect();


        //sale_id is the value returned from LAST_INSERT_ID(), which is the sale_id from the preceding entry
        $sql = "INSERT INTO funds (sale_id,fund_id,acc_id,fund_amt,fund_date) VALUES (LAST_INSERT_ID(),DEFAULT,:acc_id,fund_amt,:fund_date)";

        $query = $db->prepare($sql);

        $query->execute(array(
            ':acc_id' => $this->acc_id,
            ':fund_amt' => $this->fund_amt_total,
            ':fund_date' => $this->fund_date)
        ); //error occurs on this line
    }
}

第一個錯誤代碼:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`coop1`.`funds`, CONSTRAINT `funds_ibfk_2` FOREIGN KEY (`sale_id`) REFERENCES `sales` (`sale_id`))' in C:\wamp\www\coop1\1\classes.php on line 62

第二次錯誤代碼

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`coop1`.`funds`, CONSTRAINT `funds_ibfk_2` FOREIGN KEY (`sale_id`) REFERENCES `sales` (`sale_id`)) in C:\wamp\www\coop1\1\classes.php on line 62

LAST_INSERT_ID()僅在同一數據庫連接中有效。 您在每個類中調用database::instance()->connect() ,我想您每次都獲得一個新的連接,因此它沒有上一個INSERTLAST_INSERT_ID()

擁有funds::create()取決於最后一個查詢來自sales::create()的事實,這似乎是一個糟糕的設計。

您應該具有sales::create()返回其添加的行的ID,並將其作為參數傳遞給funds::create()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM