2
2

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.

laravel リレーション関係

Posted at

##データベーステーブルの関係は大体下記のように分けられます。

・1対1
・1対多
・多対多

##1対1
例:userとphoneの関係、基本一人には一つの番号しか持ってないですね。 

userでphoneを検索したいとき、二つの関係の定義:hasOne
phoneでuserを検索したいとき、二つは逆関係の定義:belongsTo

##1対多
例:articleとcommentの関係、一つの記事に複数のcommentが存在しますね。 

articleでcommentを検索したいとき、二つの関係の定義:hasMany
commentでarticleを検索したいとき、二つは逆関係の定義:belongsTo

##多対多
例:userとroleの関係、userが多くのroleを持ち、rolesも大勢のuserを持っています。 
二つの表の関係を別の表user_roleで結びつけます。

userでroleを検索したいとき、二つの関係の定義:belongsToMany

Models
Class User extends Model
{
 public function roles()
 {
   return this->belongsToMany('App\Role','role_user','user_id','role_id');
 }
}

roleでuserを検索したいとき、二つは逆関係の定義:belongsToMany

Models
Class Role extends Model
{
 public function users()
 {
   return this->belongsToMany('App\User','role_user','role_id','user_id');
 }
}
2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?