Help us understand the problem. What is going on with this article?

Laravel Eloquentの超基本的な使い方

自分用にまとめました

モデルの取得

主キーで取得

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

kshiva1126
都内でプログラマ3年目として働いています。 業務で使用している言語はPHPとたまにJSです。 勉強の中で気づいたことや共有したいことを書いていこうと思っています。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした