We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

insert ignore

want to add to database record with a request 'INSERT IGNORE ...' (since there are two fields associated UNIQUE).

then, after a request to receive the inserted record id (primary key autoincrement).

how to do it ??? I'm all worn out already = (



14.3k
edited Mar '15
    $sql = 'INSERT IGNORE INTO invoices VALUES (null, :emailId, :userId, :offerType)';
    $sth = $this->db->prepare($sql);
    $sth->bindParam(':emailId',   $arrInvoice['emailId'], PDO::PARAM_INT);
    $sth->bindParam(':userId',    $arrInvoice['userId'], PDO::PARAM_INT);
    $sth->bindParam(':offerType', $arrInvoice['offerType'], PDO::PARAM_INT);

    $sth->execute()

tried so, but $sth not return inserted id



14.3k
    $invoice = new invoices();
    $php->emailId = $arrInvoice['emailId'];
    $php->userId = $arrInvoice['userId'];
    $php->offerType = $arrInvoice['offerType'];
    $php->save ();

this code gives an error, because the related field is not unique



14.3k

table invoices have: UNIQUE uniqueEmailIdUserId ( emailId , userId )



10.5k
Accepted
answer

There is no way to INSERT IGNORE by Phalcon Model. But you can use RAW query by using DB adapter that added to your app DI.

BUT!!! You could use $model->save() or $model->create()exception to handle INSER IGNORE yourself. something like this:

try {
    ...
    $model->save();
    //OR
    $model->create();
} catch (Exception $e) {
    if ($e->getCode() == 1062 //DUPLICATE ERROR CODE) {
        // do nothing :) infact it handled duplicate entry by giving no error
    } else {
        throw $e; // or anything you want...
    }
}