Transaction and lock tables in Laravel

Example

        try {
            DB::beginTransaction();
            DB::raw('LOCK TABLES order WRITE, tickets WRITE');

            //logg(count($buy_tickets) > count($sell_tickets));
            if(count($buy_tickets) > count($sell_tickets)){
                //N筆買單對1筆賣單
                $this->sell_to_N($sell_tickets[0], $buy_tickets, $product);
            }else{
                //N筆賣單對1筆買單(機率應該最高)
                $this->buy_from_N($buy_tickets[0], $sell_tickets, $product);
            }

            DB::commit();
            //DB::raw('UNLOCK TABLES');

            return true;
        } catch (\Exception $e) {
            DB::rollback();
            $this->err = '撮合失敗: ' . $e->getMessage();
            return false;
        }

Reference:

  1. https://stackoverflow.com/questions/53522444/how-to-lock-table-with-laravel
  2. https://www.mysql.tw/2018/06/mysql-lock-table-lockrow-lock.html
  3. https://xyz.cinc.biz/2013/04/mysql-lock-tables.html
  4. https://laravel.com/docs/6.x/queries#pessimistic-locking