0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

リレーションを使用したシーダーの作成

0
Last updated at Posted at 2021-12-12

今回はリレーションを使用したseederの作成をしていく。

1.Postテーブルにデータを保存
カラム:id,title,content,tag,place

2.Commentsテーブルにデータを保存
カラム:id,post_id,name,article_author,content,post_tag

まずはPostModelにリレーションをはる。
1つの投稿に対して複数のコメントのデータを持つので1対多の関係になるのでhasManyになる。
第二引数には外部キーの設定が必要だが今回の場合、commentsテーブルにはpost_idというカラムがあるため第二引数は必要ない。
*以下ドキュメント参照

Eloquentは、Commentモデルに対する外部キーを自動的に決めることを心に留めてください。規約によりEloquentは、自分自身のモデル名の「スネークケース」に_idのサフィックスをつけた名前と想定します。ですから今回の例でEloquentは、Commentモデルの外部キーをpost_idであると想定します。

PostModel

    public function comment()
    {
        return $this->hasMany(Comment::class);
    }

CommentModel同様にリレーションをはる

    public function post()
    {
        return $this->belongsTo(Post::class);
    }

準備が整ったのでリレーションを使ったseederを作成する。

php artisan make:seeder hogeSeeder

作成したseederに以下のコードを書いていく

public function run()
    {

         //postテーブルにcreateメソッドでデータを作成し$postDataに代入
         //createメソッドで作成することで返り値がModelなのでリレーションが使える。
        $postData = Post::create([
            'name'       => 'hoge',
            'title'      => 'パンケーキ食べに行った',
            'content'.   => '美味しかった',
            'tag'.       => 'グルメ',
            'place'.     => '沖縄県'
        ]);

         //$postDataには作成された記事のデータが入っているのでリレーションを使ってCommentsテーブルのカラムに必要なデータを入れる
         //ちなみにpost_idはリレーションのおかけで書かなくても自動的に作成してくれる
        $postData->comment()->create(
            [
                //'post_id'      => $postData->id,
                'name'           => 'yoshiaki'
                'article_author' => $postData->name //hoge
                'content'        => '美味しそうですね!!'
                'post_tag'       => $postData->tag, //グルメ
            ]
        );
    }
}

以上がリレーションを使ったseederの作成になる。
seederの作成というよりデータの作成って感じかな....笑

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?