laravel 小モデルから親モデル取得

モデルのER図

f:id:happy_teeth_ago:20200722104409j:plain

子供のMaterialControllerに記載する場合

class MaterialsController extends Controller{

   public function index(Request $request)
    {

//リクエストスコープからidを取得
        $id = $request->id;

//Materialテーブルの group_id を取得 where は第一引数(DBカラム名)と第二引数(変数)と同じものを絞り込んでくれる
        $groupId = Materials::where('group_id', $id);

//関連づいている親のidを取得すれば、親モデルに関連づいているすべてのデータが取得できる
        $groups = Groups::where('id',$groupId);

//変数 $groups に詰め込んでViewに返してあげる
        return view('materials.index',compact('groups'));
    }