0
0

【Laravel】Eloquentとクエリビルダ

Last updated at Posted at 2023-11-06

Laravel=5.6

Eloquentとは

LaravelにおけるORMのこと。「Eloquent」=Laravel用語、「ORM」=(Laravelに限らない)一般用語。クエリビルダにもなりうる。

クエリビルダとは

SQLを便利に記述するための機能。

違い

ソフトデリートの扱い

Eloquent

ソフトデリートされたレコードを除外して取得する。

クエリビルダ

ソフトデリートされたレコードを除外しないで取得する。

データ型

Eloquent

1データ=モデル。複数データ=コレクション。

get_class(Corporate::first()); // App\Models\Corporate
get_class(Corporate::get()); // Collection

クエリビルダ

1データ=stdClass。複数データ=コレクション。

get_class(DB::table('corporates')->first()); // stdClass
get_class(DB::table('corporates')::get()); // Collection

リレーションテーブルのデータ取得

Eloquent

withを使う
Corporate.php
public function organizations () {
    $this->hasMany('Organizations');
}
Corporate::with('organizations')->get();
クエリビルダとしてjoinを使う
Corporate::join('organizations', 'corporates.id', '=', 'organizations.corporate_id')->get();

クエリビルダ

DB::table('corporates')->join('organizations', 'corporates.id', '=', 'organizations.corporate_id')->get();

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