【问题标题】:Laravel - Retrieve foreign table nameLaravel - 检索外部表名
【发布时间】:2022-01-26 00:18:03
【问题描述】:

我在一个小型 laravel 项目中遇到了简单数据之间的关系问题。

我有一个列出食谱的recipes 表,还有一个列出食谱类型的recipe_types 表。在我的recipes 表中,我有一个列recipe_types_id,它是一个引用recipe_types 表的id 列的外键。

在 Laravel 中,我有一个视图,我想在其中列出所有食谱,并在其中显示食谱名称和食谱类型名称。

一个配方只能有一种类型,但一个类型可以链接到多个配方。

现在我在配方模型中添加了这个:

public function recipeType()
{
   return $this->hasOne(RecipeType::class,'id');
}

我很确定 hasOne 的关系是正确的,但由于我遇到的问题,我开始怀疑。

在我的 RecipeController 中,我像这样检索所有帖子:

public function index()
{
    $recipes = Recipe::with('recipeType')->get();

    return view('recipes')->with('recipes', $recipes);
}

我现在遇到的问题是,当我在刀片视图中显示 ID 1 的配方(recipe_type_id 为 3)时,当我使用 {{ $recipe->recipeType->name }} 时,返回 ID 为 1 的配方类型的名称而不是 ID 为 3 的 recipe_type。

此处的数据示例、当前行为和预期行为:

=== Recipe Table ===
{id: 1, name: 'Chocolate Cake', recipe_type_id: 3},
{id: 2, name: 'Carrot soup', recipe_type_id: 1}

=== Recipe Type Table ===
{id: 1, name: 'Soup'},
{id: 2, name: 'Main plate'},
{id: 3, name: 'Dessert'}

在我现在得到的列表中(检索到的类型 ID 是配方的 ID):

  • 配方 1
    • 名称:巧克力蛋糕
    • 类型:汤
  • 配方 2
    • 名称:胡萝卜汤
    • 类型:主板

在我的清单中,我想要和应该拥有什么:

  • 配方 1
    • 名称:巧克力蛋糕
    • 类型:甜点
  • 配方 2
    • 名称:胡萝卜汤
    • 类型:汤

你知道我错过了什么吗?我阅读了文档,在 google 和 StackOverflow 上查看,我找到了我认为对我有帮助的解决方案,但他们没有,我很沮丧无法完成我认为应该简单的事情(?)

非常感谢您的帮助。

【问题讨论】:

    标签: laravel eloquent foreign-keys relationship


    【解决方案1】:

    在您的情况下,您有 Recipe 属于一个 RecipeType

    试试这样:

    public function recipeType()
    {
       return $this->belongsTo(RecipeType::class, 'recipe_types_id', 'id');
    }
    

    docs 中,您可以将模型RecipeType 想象为Post,将Recipe 想象为Comment

    Recipe只属于一个RecipeTypeRecipeType可以有多个Recipe

    希望我能帮助你理解。

    【讨论】:

    • 当我尝试这个时,我得到了这个错误:SQLSTATE[42S22]: Column not found: 1054 Unknown column 'recipe_types.recipe_type_id' in 'where clause' (SQL: select * from `recipe_types` where `recipe_types`.`recipe_type_id` in (1, 2))
    • 对不起,我更新了我的答案。您应该为您的案例使用belongsTo 关系。
    • 感谢您的帮助,我进行了更改,现在$recipe->recipeType 返回null,但是当我查看数据库时,一切似乎都很好,该类型的ID 存在于类型数据库中。我会试着找到现在缺少的东西,但这很奇怪
    • 不客气。这种方法适用于belongsTo。如果关系不好,你应该得到一些 SQL 错误。
    • 代替$recipe->recipeType,使用$recipe->recipe_type...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多