6
5

More than 5 years have passed since last update.

Laravel:リレーション

Last updated at Posted at 2018-10-04

リレーションの設定

記事とユーザーを紐付けます。

  • 記事の一覧を表示した時に、投稿者を表示できる
  • 投稿者のマイページで自分の投稿した記事だけを表示できる
  • ユーザーが削除された時に紐付く記事を消すことができる

Model にリレーションを追加する

▶ User.php

app/User.php

    /**
     * リレーション(1対多)
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function posts() // 複数形
    {
        return $this->hasMany('App\Post');
    }

▶ Post.php

app/Post.php

    /**
     * リレーション (従属)
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user() // 単数形
    {
        return $this->belongsTo('App\User');
    }

外部キー制約をつける

ユーザーの情報が削除されたら、それに紐付くpostの情報も一緒に削除するようにします。

  • postテーブルに user_id というカラムを追加する
    ここに記事の作成者のidを格納するようにします。

  • 追加カラムに外部キー制約をつける
    外部キー制約とは、テーブルの特定カラムについて格納できる値を他のテーブルに格納されている値だけに限定するものです。

▶ マイグレーションファイルを修正する

create_posts_table.php を修正します。

database/migrations/2017_05_22_041557_create_posts_table.php
     public function up()
     {
         Schema::create('posts', function (Blueprint $table) {
             (中略)
+            $table->integer('user_id')->unsigned(); //カラム追加
+            
+            $table->foreign('user_id') //外部キー制約
+                  ->references('id')->on('users') //usersテーブルのidを参照する
+                  ->onDelete('cascade');  //ユーザーが削除されたら紐付くpostsも削除
         });
     }

▶ Seederにuser_idを追加

すでにSeederを作ってあるので、これも修正します。

database/seeds/PostsTableSeeder.php
     DB::table('posts')->insert([
         (中略)
+        'user_id' => $faker->numberBetween(1, 20),
     ]);

▶ マイグレーション実行

php artisan migrate:refresh --seed

うまくいったらMySQLも確認ね

SELECT * FROM posts;

Viewを直す

▶ posts側

記事の一覧ページ(resources/views/posts/index.blade.php)
<a href="{{ url('users/' . $post->user->id) }}">
    {{ $post->user->name }}
</a>
記事1件(resources/views/posts/show.blade.php)
<a href="{{ url('users/' . $post->user->id) }}">
    {{ $post->user->name }}
</a>

▶ users側

6
5
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
6
5