1
1

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 5 years have passed since last update.

Laravel リレーションの覚え方

Posted at

混乱する人向け。

手っ取り早い考え方

  • Q1 どっちがbelongsTo()?

    • A. 外部キー(FK)がある方がbelongsTo()
  • Q2. hasMany(),hasOne()どっちを使えばいい?

    • A. belongsTo()側のTBLに、対象FKのレコードが複数回登場するならhasMany()。uniqueならhasOne()

Sample Database Table

アカウント情報

users TBL
id autoincrement PK
email string
password string
name string

アカウントユーザの住所

address TBL
id autoincrement PK
user_id FK users.id
prefecture_code string
address string

掲示板投稿

posts TBL column
id autoincrement PK
user_id FK users.id
title string

掲示板投稿に対するコメント

comment TBL column
id autoincrement PK
post_id FK posts.id
user_id FK users.id
message string

User Model

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $table = 'users';   
    
        public function address()
    {
		return $this->hasOne('App\Models\Address', 'user_id');
    }
    
    public function posts()
	{
    	return $this->hasMany('App\Models\Post', 'user_id');
	}

    public function comments()
	{
    	return $this->hasMany('App\Models\Comment', 'user_id');
	}
    
}

Address Model

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Address extends Model
{
    protected $table = 'address';   
    
    public function user()
	{
    	return $this->belongsTo('App\Models\User', 'user_id');
	}
}

Post Model

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $table = 'posts';   
    
    public function user()
	{
    	return $this->belongsTo('App\Models\User', 'user_id');
	}

    public function comments()
	{
    	return $this->hasMany('App\Models\Comment', 'post_id');
	}
}

Comment Model

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    protected $table = 'comments';   
    
    public function user()
	{
    	return $this->belongsTo('App\Models\User', 'user_id');
	}

    public function post()
	{
    	return $this->belongsTo('App\Models\Post', 'post_id');
	}
}
1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?