LoginSignup
5
13

More than 3 years have passed since last update.

Laravel Eloquentの超基本的な使い方

Last updated at Posted at 2020-02-09

モデルの取得

主キーで取得


SELECT * FROM users WHERE id = 1 LIMIT 1;

:point_down:

App\User::find(1);

全件取得

SELECT * FROM posts WHERE writer_id = 1;

:point_down:

App\Post::where('writer_id', 1)->get();

1件だけ取得

whereの引数を配列にすれば、And検索できる

SELECT * FROM favorites WHERE user_id = 1 AND post_id = 1 LIMIT 1;

:point_down:

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%';

:point_down:

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);

:point_down:

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();

:point_down:


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

5
13
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
5
13