0
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 3 years have passed since last update.

【Laravel】Railsのようにターミナル(bash)でモデルを使ってDBのデータを取得する方法

Last updated at Posted at 2021-04-22

LaravelでRailsのようにターミナル(bash)でモデルを使ってDBのデータを取得する方法について。

対処法

php artisan tinkerでphpの対話モードに入ることでモデルを介してDBのデータを取得できる。

$php artisan tinker

>>> モデルの名前空間::メソッド;

## 実例 名前空間`App\Models\User`の中のデータのid=1のデータを抽出する。
$ php artisan tinker
Psy Shell v0.9.9 (PHP 7.2.8 — cli) by Justin Hileman
>>> App\Models\User::find(1)
=> App\Models\User {#4239
     id: 1,
     name: "admin",
     email: "example@gmail.com",
     created_at: "2018-10-06 00:10:15",
     updated_at: "2019-01-24 21:16:54",
   }
>>>

find(id番号)

指定したid番号のデータを取得する。

>>> App\Models\User::find(5)

find(1)first()と同じ。


#### `all()` 全データを抽出
>>> App\Models\User::all()

#### `where('カラム名', 値)` 条件に一致するデータを抽出。whereのみではcollection型で出力されるため、データを表示するためには`first()`をつける
>>> App\Models\User::where('id', 3)->first()

#### `toSql()` SQLクエリを抽出する。
>>> App\Models\Article::where('id', 3)->toSql();
=> "select * from `articles` where `id` = ?"
0
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
0
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?