これも、前回と同様「実はそうでなかった」のトピックです。今度は、Eloquentのクエリーにおいてwhere()で条件を指定するとき。
早速、tinkerを使って具体的な例を作成します。
Psy Shell v0.9.3 (PHP 7.1.14 — cli) by Justin Hileman
>>> factory(App\User::class,2)->create()
=> Illuminate\Database\Eloquent\Collection {#2341
all: [
App\User {#2337
name: "笹田 洋介",
email: "jun91@example.com",
updated_at: "2019-03-08 08:24:36",
created_at: "2019-03-08 08:24:36",
id: 1,
},
App\User {#2333
name: "高橋 舞",
email: "hideki31@example.com",
updated_at: "2019-03-08 08:24:36",
created_at: "2019-03-08 08:24:36",
id: 2,
},
],
}
factory()を使用して、2つレコードをusersのテーブルに作成しました。これら、もちろんですが作成したばかりなので、作成時間と更新時間はどちらのレコードも同じ、つまりcreated_at == updated_at です。
ということは、where()でその条件を指定してやれば、両方のレコードとも取得できますよね。早速クエリを実行してみます。
>>> User::where('created_at', '=', 'updated_at')->get();
=> Illuminate\Database\Eloquent\Collection {#2340
all: [],
}
あれれ、結果は空ですね。この前作成した、tinkerのsql()で実行されたSQL文を見てみると、
>>> sql()
=> [
...
[
"query" => "select * from `users` where `created_at` = ?",
"bindings" => [
"updated_at",
],
"time" => 3.5,
],
]
そう、usersテーブルの項目を指定しているのでなく、文字列の“updated_at”の指定となっているのです。どうりで空の取得となるわけです。
正しくは、
>>> User::whereRaw('created_at = updated_at')->get();
=> Illuminate\Database\Eloquent\Collection {#2345
all: [
App\User {#2332
id: 1,
name: "笹田 洋介",
email: "jun91@example.com",
created_at: "2019-03-08 08:24:36",
updated_at: "2019-03-08 08:24:36",
},
App\User {#2339
id: 2,
name: "高橋 舞",
email: "hideki31@example.com",
created_at: "2019-03-08 08:24:36",
updated_at: "2019-03-08 08:24:36",
},
],
}
と、whereRaw()を使用して、生の条件文を入れてやるのです。実行されたSQL文を見てみると、
>>> sql()
=> [
...
[
"query" => "select * from `users` where created_at = updated_at",
"bindings" => [],
"time" => 0.8,
],
]
と正しいSQL文となっています。
メルマガ購読の申し込みはこちらから。