首页 > 解决方案 > Laravel Eloquent:加入表格并检索特定值?

问题描述

我对 Laravel 很陌生,我正在做一个膳食计划项目。我想要的功能之一是有一个视图来打印包含特定膳食计划中所有成分的表格。

膳食计划表

配方表

配料表

一份膳食计划有许多食谱。一个食谱有很多成分。

在显示膳食计划的视图上,我想要一个类似 的按钮,然后拉出一个视图,显示与该特定膳食计划Preview Ingredients Print list中的所有食谱相关联的所有成分。

我尝试过请求MealPlan_ID(每个单独的膳食计划的唯一标识符,它有多个食谱 ID),然后将表格连接在一起。因为 Meal Plan 表和 Ingredients 表都有Recipe_ID,Recipe Table 可以在连接中完全省略吗?

public function printpreviewingredients($MealPlan_ID)
{
    //take the Meal Plan ID, to then collect the correct Recipe ID's and all of the following ingredients.
    $ingredients = MealPlanDisplay::find($MealPlan_ID)
        ->join('recipeingredientsmain', 'recipeingredientsmain.recipe_id', '=', 'mealplan_main.Recipe_ID')
        ->get(['recipeingredientsmain.id', 'recipeingredientsmain.ingredientname', 'recipeingredientsmain.amount']);

    return view('MealPlanDisplay.printpreviewingredientslist', compact('ingredients'));
}

路线web.php是:

Route::get('printpreviewingredients/{$MealPlan_ID}', [MealPlanDisplayController::class, 'printpreviewingredients']);

然后视图printpreviwingredientslist.blade.php包含一个包含信息的表ingredients

<thead class="bg-gray-50">
    <tr>
        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
            ID
        </th>
        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
            Recipe ID
        </th>
        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
            Ingredient Name
        </th>
        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
            Amount
        </th>
    </tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
    @foreach ($ingredients as $var)
        <tr>
            <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                {{$var->id}}
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                {{$var->Recipe_Id}}
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                {{$var->ingredientname}}
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                {{$var->amount}}
            </td>
        </tr>
    @endforeach
</tbody>

不幸的是,这会返回 404 错误,并带有page not found. 我不太确定如何使用三表关系来处理这种连接和信息检索。有什么建议么?

标签: phphtmldatabaselaraveleloquent

解决方案


it is because you have defined an incorrect file in the return view. Please check your filename spelling.

For joining table using Laravel eloquent please follow this answer given below

How to join three table by laravel eloquent model


推荐阅读