how to order a JSON response based on database relationship using eloquent

后端 未结 2 1179
栀梦
栀梦 2021-01-23 01:41

I\'m quite new to Laravel and I\'m trying to figure out how to properly work with Eloquent so far so good, but I\'m stuck in something I want to do:

I have 3 tables in a

2条回答
  •  情话喂你
    2021-01-23 02:02

    Based on the picture(ie your tables) you sent food_group does not have direct relationship with the portions so you can't chain food_group with portion like this

      App\FoodGroup::with('portion.foods')
    

    it should rather be (that is why you getting BadMethodCallException in Builder::portions())

     App\FoodGroup::with('foods.portion')
    

    because foodgroup has many foods and foods has many portion. so you can try something like this

    App\FoodGroup::with(['foods.portion'=>function($q){
       $q->orderBy('id')
    }])->get(); 
    

提交回复
热议问题