0
0

More than 1 year has passed since last update.

【Laravel5系】外部キーを2つ持つテーブルのリレーション

Last updated at Posted at 2021-12-22

やりたかったこと

ツイッタークローンのアプリを作成中。
ユーザのフォロー・フォロワーの管理をするfollowsTableから、ログイン中のユーザのフォロー人数、フォロワー人数がほしい。

マイグレーション

usersのidをずっと「increments」にしててmigrateでエラーになってた。
→followsの「unsignedBigInteger」に合わせたら解消した。(合ってるのかな?)

  • usersTable
create_users_table.php
class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->unsignedBigInteger('id')->autoIncrement();
            $table->string('username',255);
            $table->string('mail',255);
            $table->string('password',255);
            $table->timestamps();
        });
    }
  • followsTable
class CreateFollowsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('follows', function (Blueprint $table) {
            $table->increments('id')->autoIncrement();
            $table->unsignedBigInteger('follow_id');
            $table->unsignedBigInteger('follower_id');
            $table->timestamp('created_at')->useCurrent();

            $table->foreign('follow_id')
            ->references('id')
            ->on('users');

            $table->foreign('follower_id')
            ->references('id')
            ->on('users');

            $table->unique(['follow_id', 'follower_id']);
        });
    }

モデル

Eloquentのリレーションを組む。
自分はusers対followsは多対多だと思っています。

  • User.php
User.php
class User extends Authenticatable
{

   // 一部省略

    public function followUsers(){
        return $this->belongsToMany('App\User', 'follows', 'follow_id', 'follower_id');
    }
    public function followerUsers(){
        return $this->belongsToMany('App\User', 'follows', 'follower_id', 'follow_id');
    }

コントローラ

ログインしているユーザの情報から、モデルで作ったfunctionを呼び出す。

HomeController.php
class HomeController extends Controller
{
    //
    public function index(){
        $user = Auth::user();

        //ログインユーザのフォローしている人数
        $follow = $user->followUsers;
        $followCount = $follow->count();

        //ログインユーザのフォローされている人数
        $follower = $user->followerUsers;
        $followerCount = $follower->count();

        return view('posts.index',compact('user', 'followCount', 'followerCount'));
    }

ビュー

コントローラで渡した変数をぶちこむ。

home.blade.php

<p>{{ $user->username }}さんの</p>
<p>フォロー数</p>
<p>{{ $followCount }}名</p>
<p>フォロワー数</p>
<p>{{ $followerCount }}名</p>

まとめ

まだまだ初学者ですが、欲しかったデータを持ってこれて感動したので初投稿しました。
もし指摘やもっといい方法があれば教えて下さい!

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