LoginSignup
1

More than 1 year has passed since last update.

【これは便利!】データ取得時、他テーブルの状態を見て取得するか判断する

Posted at

感動したコードがこちら!

userに関連する'address'テーブル内の
'country'カラムが「japan」、'area'カラムが「tokyo」の場合のuserを取得しています

$user_exist = User::whereHas('address', function ($query) {
    $query->where('country', 'japan')
        ->where('area', 'tokyo');
})->get();

Usersテーブルの構造

id
name
age
email

addressテーブルの構造

id
user_id
country
area
post_code

これで関連するデータを一度取得したり、if文foreachで判断したりと、
長々としたコードと手間が省ける!!
ラッキー!!

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
1