LoginSignup
0
0

More than 3 years have passed since last update.

Laravel クエリビルダで実行しているSQLを取得する

Posted at

# 目的

  • Laravelのクエリビルダで実行しているSQLを取得する方法をまとめる

環境

  • ハードウェア環境
項目 情報
OS macOS Catalina(10.15.5)
ハードウェア MacBook Pro (13-inch, 2020, Four Thunderbolt 3 ports)
プロセッサ 2 GHz クアッドコアIntel Core i5
メモリ 32 GB 3733 MHz LPDDR4
グラフィックス Intel Iris Plus Graphics 1536 MB
  • ソフトウェア環境
項目 情報 備考
PHP バージョン 7.4.8 Homebrewを用いてこちらの方法で導入→Mac HomebrewでPHPをインストールする
Laravel バージョン 6.X commposerを用いてこちらの方法で導入→Mac Laravelの環境構築を行う
MySQLバージョン 8.0.19 for osx10.13 on x86_64 Homwbrewを用いてこちらの方法で導入→Mac HomebrewでMySQLをインストールする

情報

  • 筆者はMacのローカルにて本記事に記載されている内容を実装し確認する。

方法

  1. 下記のようなクエリビルダの記載が任意のメソッド内にあったとする。

    $saveInfo = $this->content;
    $saveInfo['user_id'] = $saveData['userId'];
    $saveInfo['content'] = $saveData['content'];
    $saveInfo->save();
    
  2. 下記のようにすることで変数$sqlに実行直前で実行されたSQL文が格納される。

    $saveInfo = $this->content;
    $saveInfo['user_id'] = $saveData['userId'];
    $saveInfo['content'] = $saveData['content'];
    $saveInfo->save();
    $sql = $saveInfo->toSql();
    
  3. 下記のように記載することでSQL文をログに出力する事ができる。

    use Illuminate\Support\Facades\Log;
    
    $saveInfo = $this->content;
    $saveInfo['user_id'] = $saveData['userId'];
    $saveInfo['content'] = $saveData['content'];
    $saveInfo->save();
    $sql = $saveInfo->toSql();
    
    Log::info($sql);
    
  4. 実際のメソッド内部に処理を記載したものを下記に記載する。筆者はRepositoryにDBアクセス処理を記載している。

    アプリ名ディレクトリ/Repositories/ContntRepository.php
    <?php
    
    namespace App\Repositories;
    
    use App\Repositories\ContentRepositoryInterface;
    use App\Models\Content;
    use Illuminate\Support\Facades\Log;
    
    class ContentRepository implements ContentRepositoryInterface
    {
        /**
         * @var Content
         */
        private $content;
    
        public function __construct(Content $content)
        {
          $this->content = $content;  
        }
    
        /**
         * 全ての投稿内容を取得する
         *
         * @return Content|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null
         */
        public function getContentAll()
        {
            return $this->content->all();
        }
    
        public function saveContent($saveData)
        {
            $saveInfo = $this->content;
            $saveInfo['user_id'] = $saveData['userId'];
            $saveInfo['content'] = $saveData['content'];
            $saveInfo->save();
            $sql = $saveInfo->toSql();
            Log::info($sql);
    
            return true;   
        }
    }
    
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0