ホーム » モデルデータの操作方法について

モデルデータの操作方法について

モデルデータの取得方法について

// よく利用するデータ取得方法
$books = Book::all();
$books = Book::find(1); // id指定、値がないとnull
$books = Book::first(); // 1番目の値を取得(最初のレコードを返す

// 複数ID取得(collectionで取得)
$books = Book::find([1,2,3]);

// モデルデータの取得時によく利用するwhere句について
$books = Book::where('id', 1)->get(); // id指定
$books = Book::where('id', 1)->toSql(); // sql文を表示
Book::where('test1', 1)->dd(); // sql文を表示(toSqlより詳しい情報)
$books = Book::where('id', 1)->where('name', 'test')->get(); // andの場合は、whereをメソッドチェーンで利用する
$books = Book::whereIn('id', [1])->get(); // where in
$books = Book::where('name', 'like', '%test%')->get(); // where like
$books = Book::where('id', 1)->select('id', 'name')->get(); // select句

// join(結合)
$books = Book::leftjoin('tags', 'books.id', '=', 'tags.book_id')->get(); // left join
$books = Book::rightjoin('tags', 'books.id', '=', 'tags.book_id')->get(); // right join
$books = Book::leftjoinSub('tags', 'books.id', '=', 'tags.book_id')->get(); // left join
$books = Book::rightjoinSub('tags', 'books.id', '=', 'tags.book_id')->get(); // right join

// subQuery(サブクエリ)
$subQuery = Book::find(1)->toSql();
Book::leftjoinSub($subQuery ,'book_sub', 'books.id', '=', 'book_sub.id')->toSql();
 
// oderByの書き方と短く書く方法について
$books = Book::orderBy('id', 'asc')->get(); // asc 昇順
$books = Book::orderBy('id', 'desc')->get(); // desc 降順
$books = Book::orderBy('id')->get(); // デフォルト asc
$books = Book::latest('id');
$books = Book::oldest('id');

// レコードを新しい順(desc)降順に並び替える事が出来ます。
Book::latest()->get();
・latestを使わない場合はこうなります。
Book::orderBy('created_at', 'desc')->get();
・初期値はcreated_atになり、それ以外のカラムを利用したい場合はこうなります。
Book::latest('name')->get();

// レコードを古い順(asc)昇順に並び替える事が出来ます。
Book::oldest()->get();
・oldestを使わない場合はこうなります。
Book::orderBy('created_at', 'asc')->get();
・初期値はcreated_atになり、それ以外のカラムを利用したい場合はこうなります。
Book::oldest('name')->get();

// 通常のグループ化
Item::select('name')->groupBy('name')->get();

// 複数指定
Item::select('name', 'status')->groupBy('name', 'status')->get();

// DB::rayを利用したグループ化で件数を取得する場合
Item::groupBy('name')->select('name', DB::raw('count(*) as total'))->get();

// 簡潔に書く方法
Item::groupBy('name')->get('name');

// グループ化した後に条件検索する場合
Item::groupBy('name')->having('name', '=', 'aaaa')->get('name');
Item::groupBy('name')->having('name', 'aaaa')->get('name');


// update
$books = Book::where('id', 1)->update(['name' => 'test2']);

// insert
$books = Book::insert(['name' => 'test3']);

// delete
$books = Book::where('id', 2)->delete();

論理削除の設定

// soft deleteをカラム追加する。migrationのup、downに下記を設定します。
// up
$table->softDeletes();
// down
$table->dropSoftDeletes();
<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes; // これを追加

class Book extends Model
{
    use HasFactory;
    use SoftDeletes;  // これを追加
}

モデルデータを更新する方法について

// クエリビルダを利用したupdate
// updateはupdated_atが更新されます。
Item::where('id', 1)->update(['name' => 'imanaka']);

// saveメソッドを利用したupdate
$item = Item::find(1);
$item->name = 'imanakaM';
$item->save();

// 複数更新
Item::where('id', 1)->update(['name' => 'imanaka', 'status' => 'stop!']);

$item = Item::find(1);
$item->name = 'Mimanaka';
$item->status = 'gogogo!';
$item->save();

特定のカラムの増分、減分

// 下準備
sail php artisan make:migration add_support_id_in_items_table

// up
$table->integer('support_id');
// down
$table->dropColumn('support_id');

// 増分
Item::find(1)->increment('support_id');
Item::find(1)->increment('support_id', 2);

// 減分
Item::find(1)->decrement('support_id');
Item::find(1)->decrement('support_id', 2);

// 同時に別の更新するカラムを指定することもできます。
Item::increment('support_id', 1, ['name' => 'John']);

モデルデータを挿入する方法について

// 1件挿入
// insertはcreated_at、updated_atが更新されない
Item::insert(['name' => 'tanaka', 'status' => 'go', 'support_id' => 1]);

// 複数レコード挿入
Item::insert([
	['name' => 'tanaka', 'status' => 'go', 'support_id' => 1],
	['name' => 'suzuki', 'status' => 'no', 'support_id' => 2],
]);

// insertした際に、新しいレコードのID値を取得する
$id = Item::insertGetId(
    ['name' => 'saitou', 'status' => 'gogo', 'support_id' => 1]
);

// saveメソッドを利用する(created_at、updated_atが更新される)
$item = new Item();
$item->name = 'takahashi';
$item->status = 'nono!';
$item->support_id = 3;
$item->save();

// created_at、updated_atが更新される
Item::create([
    'name' => 'yamamoto',
    'status' => 'go',
    'support_id' => 1
]);

モデルデータを削除する方法について

// 通常のdelete
$deleted = Item::find(1)->delete();

// where句
$deleted = Item::where('id', 1)->delete();

// 主キーによる既存モデルの削除
// メリットは、whereする必要がない事です。

Item::destroy(1);
Item::destroy(1, 2, 3);

Item::destroy([1, 2, 3]);
Item::destroy(collect([1, 2, 3]));

// トランケート
Item::truncate();

// withTrashed
// ソフトデリート済みモデルを検索に含める
$item = Item::withTrashed()
                ->where('support_id', 1)
                ->get();

// onlyTrashed
// ソフトデリート済のモデルのみ取得する
$item = Item::onlyTrashed()

// ソフトデリートしたモデルを復元する
$item->restore();

// モデルの完全な削除をする
$item->forceDelete();

デバッグ方法

// sql文を確認する
DB::table('users')->where('votes', '>', 100)->toSql();

// sql文を確認する。詳細情報も出力
DB::table('users')->where('votes', '>', 100)->dd();

// sql文を確認する。更に詳細情報も出力
DB::table('users')->where('votes', '>', 100)->dump();

// sql文を確認する。toSqlとかで表示されない場合は、こちらを利用すると詳細情報も出力される
DB::enableQueryLog()
Item::find(1)
DB::getQueryLog()

素のSQL

Eloquent、クエリビルダで対応が難しい場合は素のSQLを書くことも出来ます。
ただし、SQLインジェクションの脆弱性を含めぬように注意が必要です。

// DB::ray
Item::select(DB::raw('count(*) as user_count, status'))->where('status', '<>', 1)->groupBy('status')->get();

// selectRaw
// 第2引数にバインディングのオプション配列を入れる
Product::selectRaw('support_id * ? as support_rate', [2])->get();

// whereRaw/orWhereRaw
// 第2引数にバインディングのオプション配列を入れる
Item::whereRaw('price > IF(state = "TX", ?, 100)', [200])

// orderByRaw
->orderByRaw('updated_at - created_at DESC')

// groupByRaw
->groupByRaw('city, state')

コメントする

メールアドレスが公開されることはありません。 が付いている欄は必須項目です