LoginSignup
0
0

More than 5 years have passed since last update.

laravelでサブクエリを使ってみた

Posted at

やりたい事

下記テーブルから30才未満のユーザーが所持している発売から1年以内の携帯を取得したい。

users_table
+----+---------------+-----------+-----+
| id | name          | phones_id | age |
+----+---------------+-----------+-----|
|  1 | XXX           | 1         | 25  |
|  2 | XXX           | 2         | 30  |
|  3 | XXX           | 3         | 21  |
+----+---------------+-----------+-----|
phones_table
+----+---------------+---------------------|
| id | number        | release_date        |
+----+---------------+---------------------|
|  1 | XXX-XXXX-XXXX | 2018-11-01 00:00:00 |
|  2 | XXX-XXXX-XXXX | 2017-11-01 00:00:00 |
|  3 | XXX-XXXX-XXXX | 2016-11-01 00:00:00 |
+----+---------------+---------------------|

コード

php
$lastYear = date("Y-m-d H:i:s", strtotime("-1 year"));
$data = Phone:where('release_date', '>', $lastYear)
    ->whereIn('id', function($query)
        {
            $query->select(DB::raw('phones_id'))
                  ->from('users')
                  ->whereRaw('age < 30');
        }
    )
    ->get();
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