If Update else Insert Into exists. MySQL - PHP

I ask this question to find the best practice for this.

DB::table('owners')
   ->where('property_id',$id)
   ->update(array('person_id'=>$owner));

The problem is that the table ownersmay not have a row to update. In this case, I need to do INSERT INTOinstead UPDATE.

My problem is that I have to run 2 requests each time, one to check if a row exists, and another one to UPDATEeither INSERT INTO. Is it correct to run 2 queries each time? Is there a better way to achieve this? I need to support fast processes for the user.

UPDATE: The table ownersis the middle table of many, many relationships. Sorry, I can’t use ON DUPLICATE KEY.

+4
source share
2 answers

, firstOrCreate Laravel, , . else, . firstOrCreate , , , + 1 .

firstOrNew, , , , , , .

firstOrNew

.

public function getFirstUserOrNew($email)
   {

      $user = User::firstOrNew(['email' => $email]);

      if($user)
      {
        $this->UpdateUser($user);
      }
      else
      {
       $this->CreateUser($user);
      }
   }

    public function UpdateUser(User $user)
    {
      //Do update stuff
    }

    public function CreateUser(User $user)
    {
      //Do create stuff
    }

P.S - , - , :)

EDIT: @Pyton , updateOrCreate, .

+3

, updateOrCreate

$owner = Owner::updateOrCreate(['property_id' => $id], ['person_id'=>$owner]);
0

Source: https://habr.com/ru/post/1589412/


All Articles