Delete Duplicate Deals

1 month ago

DaftMonk

Code

collect(DB::select("
    select *, count(*) as blueVineDeals 
    from deals 
    where loanProductId = 837
    group by borrowerId 
    having count(*) > 1
"))->each(function ($row) {
    $borrower = Borrower::find($row['borrowerId']);
    $deals = Deal::where('borrowerId', $row['borrowerId'])
      ->where('loanProductId', 837)->orderBy('created', 'desc')->get();
    $realDeal = $deals->first();
    $updatedDeal = $deals->where('status', '!=', 'awaitingResponse')->first();
    if ($updatedDeal) {
      $realDeal = $updatedDeal;
    }
    $deals->each(function($deal) use ($realDeal) {
        if ($deal->id !== $realDeal->id) {
            $deal->delete(); echo $deal->id . ",\n";
        }
    });
});

Output