1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

laravel DB関係個人的メモ

Last updated at Posted at 2019-03-24

◆Modelクラス

$guarded = ['id', 'created_at']; 編集不可のものを指定する

◆findメソッド

findでデータがない場合を考慮している処理を入れている場合はいいが、それが考慮されていない場合はfindOrFailを使う

try{
 findOrFail
}catch(ModelNotFoundException $e){}

◆where

汎用的なメソッドを作成するときにwhere('カラム名', 値)を使うが、それ以外は
whereカラム名(値)で検索したほうが可読性が上がるかもしれない 
例:whereName('山田')

◆create・save・insert

◆物理削除

delete()もしくはdestory() destoryはidで指定する

◆論理削除

マイグレーションファイルに

$table->softDeletes();

テーブルにdeleted_atが追加される。そのマイグレーションファイルのテーブルに対応したModelクラスに

use SoftDeletes;

を追加しておく。

こうしておくとdelete()・destroy()を使用した際に、自動的にdeleted_atカラムに
削除時間が登録されて、データを取得する際に、自動で含まれなくなる。
例 User::get();

取得方法
User::withTrashed()->get; 削除済みを含むすべてのデータ
User::onlyTrashed()->get();削除済みのみのデータ

◆リレーション

1対1 hasOne・belongsTo

  • hasOne
    つなげる元のModelクラスに
    hasOne(つなげ先のModel, 内部キー, 外部キー);

  • belongsTo
    つなげられるModelクラスに
    belongsTo(つなげ元のModel, 内部キー, 外部キー);

内部キーと外部キーは省略することも可能で、省略時
内部キーは「モデル名_id」、外部キーは「id」が適用される。

一対多 hasMany

hasManyは基本的にhasOneと指定方法は同じでデータの在り方が1対1なのか1対多の違いだけで、引数も同じ

Laravel Eloquent最後の一行取得

$last= Model::query()->limit()->orderByDesc('id')->first();

idをオートインクリメントにした場合は、これで一番後ろ取得可能

laravelでDBトランザクション(エラーログ付き)(メモ)

DB::beginTransaction();
try {
    データベース更新処理
    DB::commit();
} catch (\Exception $e) {
    DB::rollback();
    Log::error($e->getMessage(). PHP_EOL. $e->getTraceAsString());
}

・\ExceptionのgetMessage()は例外メッセージ取得
・\ExceptionのgetTraceAsString()は例外スタックトレースを文字列取得

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?