Linked Questions

Popular Questions

How to exchange values between 2 records at unique column

Asked by At

How to exchange the values in the Unique column of two records?

like below Model

User
  id
  name
  code // this is unique

What I want to do is like...

$user1 = User::find(1);
$user2 = User::find(2);

DB::Transaction();
try {
    $user1->code = $user2->code;
    $user2->code = $user1->code;
    $user1->save();
    $user2->save();
} catch()...

of course, I know this code doesn't work by constraint violation error.

Anyway,I want to exchange UserA's code and UserB's code. But I don't know the best way.

Any one knows?

I tried this code,and it worked.but it seems little dirty.

$user1 = User::find(1);
$user2 = User::find(2);

DB::Transaction();
try {
        $user1_code_temp = $user1->code;
        $user2_code_temp = $user2->code;
    $user1->code = rand();
        $user1->save();
    $user2->code = $user1_code_temp;
    $user2->save();
        $user1->code = $user2_code_temp
    $user1->save();
} catch()...

Related Questions