MySQL完整性约束违反:1452


MySQL Integrity constraint violation: 1452

我得到一个错误,告诉我表funds中列sale_id的值在表sales中不存在。这个值是通过获取前一个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(),我猜你每次都得到一个新的连接,所以它没有以前的INSERT中的LAST_INSERT_ID()

funds::create()依赖于最后一个查询来自sales::create()的事实,这似乎也是一个糟糕的设计。

您应该让sales::create()返回它添加的行ID,并将其作为参数传递给funds::create()