【问题标题】:How to display a list of elements from a different table in a blade view?如何在刀片视图中显示来自不同表的元素列表?
【发布时间】: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-&gt;amount}} 而不是{{$var-&gt;recipeingredientsmain.amount}}

标签: php html database laravel


【解决方案1】:

在您的刀片中,通过删除表名 recipeingredientsmain 使用以下代码

<div class="flex flex-col">
    @foreach ($datatest as $var)
        <p> {{$var->amount}} </p>
        <p> {{$var->ingredientname}} </p>
    @endforeach
</div>

【讨论】:

    猜你喜欢
    • 2020-06-01
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    • 2017-04-29
    • 1970-01-01
    • 2019-08-31
    • 2021-06-24
    相关资源
    最近更新 更多