I got and issue with relationships between simple data in a small laravel project.
I have a recipes
table that list recipes, and I got a recipe_types
table listing the type of recipe. In my recipes
table, I got a column recipe_types_id
that is a foreign key referring to the id
column of the recipe_types
table.
In Laravel, I have a view, where I want to list all the recipes, where I show the Recipe Name and the Recipe Type name.
A recipe can only have 1 type, but a type can be linked to multiple recipes.
Now in the Recipe model I added this:
public function recipeType()
{
return $this->hasOne(RecipeType::class,'id');
}
I am pretty sure that the relationship hasOne is the right one, but because of the issue I have, I start having doubts.
and in my RecipeController, I retrieve all the post like this :
public function index()
{
$recipes = Recipe::with('recipeType')->get();
return view('recipes')->with('recipes', $recipes);
}
The issue I have right now, it's that when I display in my blade view the Recipe of ID 1 (with a recipe_type_id of 3), when I Use {{ $recipe->recipeType->name }}
, that return the name of the recipe_type with the ID 1 and not the recipe_type with the ID 3.
Here example of the data, current behavior and expected behavior :
=== 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'}
In my listing what I got now (the type ID retrieved is the ID of the Recipe):
- Recipe 1
- Name: Chocolate Cake
- Type: Soup
- Recipe 2
- Name: Carrot soup
- Type: Main plate
In my listing what I want and should have :
- Recipe 1
- Name: Chocolate Cake
- Type: Dessert
- Recipe 2
- Name: Carrot soup
- Type: Soup
Have you an idea of what I have been missing? I read the documentation, look on google and here on StackOverflow, I found solutions that I thought would help me, but they didn't, and I become frustrated not been able to complete what should be simple I think(?)
Thank you very much for your help.
CodePudding user response:
In your case, you have Recipe
which belongs to one RecipeType
.
Try like this:
public function recipeType()
{
return $this->belongsTo(RecipeType::class, 'recipe_types_id', 'id');
}
In the docs you can imagine your model RecipeType
as Post
and Recipe
as Comment
.
Recipe
belongs to only one RecipeType
, RecipeType
can have many Recipe
.
I hope I helped you to understand.