モデルの取得
主キーで取得
SELECT * FROM users WHERE id = 1 LIMIT 1;
App\User::find(1);
全件取得
SELECT * FROM posts WHERE writer_id = 1;
App\Post::where('writer_id', 1)->get();
1件だけ取得
whereの引数を配列にすれば、And検索できる
SELECT * FROM favorites WHERE user_id = 1 AND post_id = 1 LIMIT 1;
App\Favorite::where([
'user_id' => 1,
'post_id' => 1,
])->first();
Or検索
And検索は ->where()->where()
のようにメソッドチェーンでも書ける
また、メソッドチェーンは Or検索も表せる
SELECT * FROM posts WHERE title LIKE '%Lorem' OR title LIKE '%ipsum%';
App\Post::where('title', 'LIKE', '%Lorem')
->orWhere('title', 'LIKE', '%ipsum%')
->get();
複雑な検索
コールバックを使用すれば複雑な条件も表せる
SELECT * FROM posts
WHERE (title LIKE '%Lorem' OR title LIKE '%ipsum%')
AND (created_at IS NULL OR updated_at IS NULL);
App\Post::where(function ($query) {
return $query
->where('title', 'LIKE', '%Lorem')
->orWhere('title', 'LIKE', '%ipsum%');
})
->where(function ($query) {
return $query
->whereNull('created_at')
->orWhereNull('updated_at');
})->get();
モデルの作成
INSERT INTO favorites (user_id, post_id) VALUES (1, 2);
App\Favorite::create([
'user_id' => 1,
'post_id' => 2,
]);
モデルの更新
UPDATE posts SET updated_at = NOW();
App\Post::query()->update([
'updated_at' => \Carbon\Carbon::now(),
]);
モデルの(物理)削除
DELETE FROM favorites WHERE user_id = 1 AND post_id = 1;
App\Favorite::where([
'user_id' => 1,
'post_id' => 1,
])->delete();
参考ページ
https://readouble.com/laravel/6.x/ja/eloquent.html
https://stackoverflow.com/questions/19325312/how-to-create-multiple-where-clause-query-using-laravel-eloquent
https://stackoverflow.com/questions/15622710/how-to-set-every-row-to-the-same-value-with-laravels-eloquent-fluent