混乱する人向け。
手っ取り早い考え方
-
Q1 どっちが
belongsTo()?- A. 外部キー(FK)がある方が
belongsTo()
- A. 外部キー(FK)がある方が
-
Q2.
hasMany(),hasOne()どっちを使えばいい?- A.
belongsTo()側のTBLに、対象FKのレコードが複数回登場するならhasMany()。uniqueならhasOne()
- A.
Sample Database Table
アカウント情報
| users TBL | 型 |
|---|---|
| id | autoincrement PK |
| 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');
}
}