Modelはデータベースのテーブルあるいはビューを表す。
php artisan make:model でapp\Modelsへ作成される。
前のバージョンではapp直下に作成されていたが、8から改善されている。
名称は単数形。複数形の名称のデータベーステーブルに対応するが、
使用するテーブルあるいはビューを明示してもよい。
protected $table = 'stores';
主キーの登録やタイムスタンプ使用の有無なども登録。
public $primaryKey = 'id';
public $timestamps = true;
入力できる項目、或いは入力不要の項目など登録。
入力する項目:protected $fillable = [ ]
入力しない項目:protected $guarded = [ ]
ルールもControllerのアクションに書くより、モデルの方が効率的だが、配列の書き方など制限があるようで、
Requestに別ファイルを作成した方がよいと思います。
リレーションの登録
親の場合:authority のモデル:Authority
子としてauthority_rollが複数登録される。
public function authority_rolls()
{
return $this -> hasMany('App\Models\Authority_Roll');
}
これで、authority->authority_rollsとするとauthority_rollの配列が返ってくる。(複数形)
子の場合:authority_roll のモデル:Authority_Roll
親一人 authority。
public function authority()
{
return $this -> belongsTo('App\Models\Authority');
}
これで、authority_roll->authorityでauthorityが取得できる。