【发布时间】:2021-10-08 20:04:11
【问题描述】:
我在一个膳食计划应用程序上有一个食谱信息视图,用户可以在其中查看如何准备从其食谱 ID 中提取的食谱的具体细节。配方的成分信息存储在不同的表中,我正在尝试使用与当前正在检查的配方相同的 Recipe_ID 提取所有成分名称和相应的成分数量。配方和成分是一对多的关系。
控制器:
public function recipeinformation($Recipe_ID)
{
$datatest = Ingredients::join('mealplan_main', 'mealplan_main.Recipe_ID', '=', 'recipeingredientsmain.Recipe_ID')
->where('mealplan_main.recipe_id', '=', $Recipe_ID)
->get([ 'recipeingredientsmain.ingredientname', 'recipeingredientsmain.amount']);
$dat = Recipe::find($Recipe_ID);
return view('MealPlanDisplay.recipeinformation', compact('dat', 'Recipe_ID', 'datatest'));
}
观点:
//this works
<div class="flex flex-col">
<h3> {{$dat->recipe_name}} </h3>
</div>
//the attempt to display the ingredientname and ingredient amount does not work
<div class="flex flex-col">
@foreach ($datatest as $var)
<p> {{$var->recipeingredientsmain.amount}} </p>
<p> {{$var->recipeingredientsmain.ingredientname}} </p>
@endforeach
</div>
代码运行,但信息未显示在视图上。当我删除 foreachloop 时,我收到错误: 此集合实例上不存在属性 [recipeingredientsmain]。
如何让它正常工作?
【问题讨论】:
-
尝试转储
$datatest变量以查看它是否实际上包含任何内容,或者它是否只是一个空集合。在return之前添加ddd($datatest);。 -
尝试使用
{{$var->amount}}而不是{{$var->recipeingredientsmain.amount}}