LoginSignup
237
252

More than 5 years have passed since last update.

【Laravel】Eloquentのメソッド、プロパティ簡単まとめ

Posted at

Laravelの Eloquent について初心者の私が勉強した時に簡単にまとめてみました。
間違い等があれば、指摘お願いします。

Eloquentとは

DBとモデルオブジェクトを対応付ける機能。

Eloquentモデルでよく使うプロパティ

プロパティ 説明 規定値
$connection どのDB接続するのか。onメソッドで動的に変更可
$table どのtableに対して処理するのか (モデル名の複数形)
$primaryKey 主キーの設定 id
$incrementing 主キーをオートインクリメントするかどうか true
$timestamps テーブルの作成、更新日時を自動更新 true
$fillable 渡した属性を複数代入させるかどうか(columnに値を入れたい場合必須) null
$guarded 複数代入させないcolumnの指定($fillableと対) [*] 全てのcolumnが複数代入できない
$hidden モデルを配列/JSON変換するときに隠蔽されるcolumnの指定 null
$visible $hiddenと対 [*]

よく使うメソッド

メソッド名 内容
find 主キーを指定して検索
where 検索条件を指定 orWhere や引数でAND, OR検索ができる
count 件数を取得する
first データを1件だけ取得する
toArray データを配列に変換
toJson データをJSONに変換
create, save データの作成。createの場合は、モデルのfillableの設定が必須
insert 複数のデータを一括作成
update, save データの更新
delete, destroy データの削除。destroyは主キーを複数指定して削除可能

App\User::find(1);
=> App\User {
     id: 1,
     name: "hoge hoge",
     email: "hoge@hoge.com",
     created_at: "2015-11-11 11:11:11",
     updated_at: "2015-11-11 11:11:11",
   }

よく使う検索条件をメソッド化

メソッドの先頭にscopeをつけるとクエリスコープが定義できる。
呼び出しはscopeを外したメソッド名()

論理削除

設定

マイグレーションファイルに以下を追加

$table->softDeletes();

使用

use Illuminate\Database\Eloquent\SoftDeletes;

をモデルに追加して使用する。
通常のdelete, destroyでdeleted_atに削除時間がセットされる。
モデルでの検索時に論理削除したデータは結果に含まれない

メソッド

  • withTrashed 論理削除したデータを検索結果に含める
  • onlyTrashed 論理削除したデータのみ検索対象にする
  • restore 論理削除したデータを復元する
  • forceDelete 論理削除対象のモデルを物理削除する

リレーション

関係 備考
1:1 hasOne belongsTo
1:N hasMany belongsTo
N:N belongsToMany belongsToMany 中間テーブル必要

1:N

メールアドレス等を持ったusersテーブル(親)とつぶやき情報を持ったtweetsテーブル(子)があるとすると

Userモデル
class User extends Model 
{ 
    public function tweet()
    { 
        return $this->hasMany(Tweet::class); 
    }
}
Tweetモデル
class Tweet extends Model 
{ 
    public function user()
    { 
        return $this->belongsTo(User::class); 
    }
}

N+1問題対策

Eagerローディングはwithメソッドを用いる。

上のusersとtweetsを例に、tweetに紐付いたユーザを取得し、表示したい場合等

$tweets = App\Tweet::with('user')->get();
237
252
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
237
252