Home > Back-end >  Laravel unexpected result with WHERE and EXISTS
Laravel unexpected result with WHERE and EXISTS

Time:01-11

I have made a few Laravel application (Mainly Laravel Zero) and I have not seen this type of issue before.

I have an array which consists of 3 strings, and 3 indexes. The plan is to foreach through this array to check if the values already exist in the database, I have never had issues with Eloquent before but it appears to be having some unexpected results?

foreach ($transaction as $transactions)
{
            // Check if TX exists
            $exists = $database->where('txid', '=', $transactions['txid'])->toSql();
            echo $exists . "\n"; 
}

Each time it goes around the loop, the query changes - the first iteration returns true when using exists() but anything after that is false when it should be true.

Output results of toSql();

select * from `transactions_incoming` where `txid` = ?
select * from `transactions_incoming` where `txid` = ? and `txid` = ?

Expected results of toSql();

select * from `transactions_incoming` where `txid` = ?
select * from `transactions_incoming` where `txid` = ?

CodePudding user response:

What is $database in your case? make sure $database is initialized every time your loop is executed as new for example

assuming your $database is transaction's model object

foreach ($transaction as $transactions)
{
    $database = new Transaction();
    // Check if TX exists
    $exists = $database->where('txid', '=', $transactions['txid'])->toSql();
    echo $exists . "\n"; 
}    
  • Related