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?

Laravelのリレーションについて

Posted at

リレーションとは

Laravelではテーブルに対応したModelを定義することにより、関連を明示することでデータをうまく扱うことができる。
テーブル同士の関連の種類は、1対1、1対多、多対多、その他にも関係の構文がある。

リレーション種類

名前 説明
hasOne 1対1(親→子) ユーザー → プロフィール
belongsTo 1対1(子→親) プロフィール → ユーザー
hasMany 1対多(親→子) ユーザー → 投稿(複数)
belongsToMany 多対多(中間テーブルあり) 投稿 ↔ タグ
hasManyThrough 間接的な1対多(2段階) 国 → 投稿(ユーザー経由)
morphManyなど ポリモーフィック(多形) 画像を投稿にも商品にも付けたい等

リレーションの実装例

① ユーザー(User)と投稿(Post)の関係

models/User.php
public function posts()
{
    return $this->hasMany(Post::class);
}

users.id ← posts.user_id で紐付く

models/Post.php
public function posts()
{
    return $this->hasMany(Post::class);
}

使用例

$user = User::find(1);
$posts = $user->posts; // そのユーザーの投稿一覧

$post = Post::find(10);
$user = $post->user;   // 投稿をしたユーザー

②多対多(belongsToMany)【例:投稿とタグ】

中間テーブル:post_tag(post_id, tag_id)

models/Post.php
public function tags()
{
    return $this->belongsToMany(Tag::class);
}
models/Tag.php
public function posts()
{
    return $this->belongsToMany(Post::class);
}

使用例

$post = Post::find(1);
$tags = $post->tags; // 投稿に付いてるタグ一覧

$tag = Tag::find(2);
$posts = $tag->posts; // このタグがついている投稿一覧

関連データの一括取得

// 投稿とその投稿者をまとめて取得
$posts = Post::with('user')->get();
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?