コードロード

エラー討伐

【Laravel】多対多でリレーション先のデータを取得する

多対多のER図

リレーション先を取得する

  • モデルで追加したメソッド名を with('メソッド名') の引数に追加する
    • ※リレーション先のテーブル名やクラス名をwith()の引数にするわけではない!
// App/Models/Food.php

    /**
     * foodを持っているフードアイコン
     */
    public function foodIcons()
    {
      return $this->belongsToMany(FoodIcon::class, 'food_food_icon', 'food_id', 'food_icon_id')
                  ->withTimestamps();
    }
// app/Http/Controllers/FoodController.php

    public function index()
    {
        $foods = Food::->with('foodIcons')->get();
        return response()->json('foods' => $foods);
    }