我在一個小型 laravel 專案中遇到了簡單資料之間的關系并提出了問題。
我有一個recipes列出食譜的表格,我有一個列出食譜recipe_types型別的表格。在我的recipes表中,我有一個列recipe_types_id是參考表id列的外鍵recipe_types。
在 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 的 recipe_type 的名稱,而不是帶有身份證 3。
以下是資料、當前行為和預期行為的示例:
=== 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
- 名稱:胡蘿卜湯
- 型別:湯
你知道我錯過了什么嗎?我閱讀了檔案,在谷歌和 StackOverflow 上查看,我找到了我認為對我有幫助的解決方案,但他們沒有,我感到很沮喪,無法完成我認為應該很簡單的事情(?)
非常感謝您的幫助。
uj5u.com熱心網友回復:
在您的情況下,您擁有Recipewhich 屬于 one RecipeType。
像這樣嘗試:
public function recipeType()
{
return $this->belongsTo(RecipeType::class, 'recipe_types_id', 'id');
}
在檔案,你能想象你的模型RecipeType作為Post與Recipe作為Comment。
Recipe只屬于一個RecipeType,RecipeType可以有很多Recipe。
我希望我幫助你理解。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/394009.html
下一篇:Laravel同時插入資料庫
