LoginSignup
1
2

More than 1 year has passed since last update.

【Laravelクエリビルダ】joinで内部結合し、結合先のデータを取得する方法

Last updated at Posted at 2021-07-17

laravelのクエリビルダでjoinを用いた内部結合について簡単に解説していきます。

バージョンは6系です。

ゴール

postsテーブルのuser_idとusersテーブルのidを内部結合する。

postsテーブル
スクリーンショット 2021-07-18 0.58.48.png

usersテーブル
スクリーンショット 2021-07-18 0.59.00.png

スクリーンショット 2021-07-18 1.02.15.png

内部結合したことにより、postsテーブルのuser_idとusersテーブルのidが一致するようにデータが取得できます。

SQLで書くと以下です。

SELECT *
FROM posts
INNER JOIN users
ON posts.user_id = users.id

サンプルコード

モデル(Post.php)

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Post extends Model
{
  public function getUserNameById()
  {
    return DB::table('posts')
            ->join('users', 'posts.user_id', '=', 'users.id')
            ->get();
  }
}

join('テーブル名', '結合するテーブル名.カラム', '=', '結合先のテーブル名.カラム')
これで内部結合ができます。

ちなみに以下のようにも書き換えられます。

    return DB::table('posts')
            ->join('users', function($join) {
              $join->on('posts.user_id', 'users.id');
            })
            ->get();

詳細はlaravelの公式を参照ください。
https://search.readouble.com/?query=6.x+%E3%82%AF%E3%82%A8%E3%83%AA%E3%83%93%E3%83%AB%E3%83%80

コントローラー(PostController.php)

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;

class PostController extends Controller
{
    public function index()
    {
        $this->posts = new Post();

        $results = $this->posts->getUserNameById();

        return view('posts.index', compact(
            'results',
        ));
    }
}

ビュー(index.blade.php)

<table>
    <thead>
      <tr>
        <th>ユーザーID</th>
        <th>ユーザー名</th>
        <th>投稿名</th>
      </tr>
    </thead>
    <tbody>
    @foreach ($results as $result)
      <tr>
        <td>{{ $result->id }}</td>
        <td>{{ $result->name }}</td>
        <td>{{ $result->post_name }}</td>
      </tr>
    @endforeach
    </tbody>
</table>

このようにデータが取得できました。
スクリーンショット 2021-07-18 1.06.13.png

他にもクエリビルダについて解説した記事があるので合わせてチェックお願いします。
参考になりましたら、LGTM・ストックも!

1
2
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
1
2