Laravel N+1 beim Zugriff auf eine Pivot -Beziehung und das zugehörige Modell (Einheit)Php

PHP-Programmierer chatten hier
Anonymous
 Laravel N+1 beim Zugriff auf eine Pivot -Beziehung und das zugehörige Modell (Einheit)

Post by Anonymous »

Ich habe eine N+1 -Abfrage, während ich mit meinen Modellen arbeite und mit meinen Modellen und drehst

Code: Select all

    public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}

public function ingredients(): BelongsToMany
{
return $this->belongsToMany(Ingredient::class)
->using(IngredientRecipe::class)
->withTimestamps()
->withPivot(['quantity', 'unit_id']);
}
ingRedientRecipe.php (Pivot):

Code: Select all

    public function unit(): BelongsTo
{
return $this->belongsTo(Unit::class);
}
ingRedient.php:

Code: Select all

    public function recipes(): BelongsToMany
{
return $this->belongsToMany(Recipe::class);
}
unit.php:

Code: Select all

    public function ingredient_recipes(): HasMany
{
return $this->hasMany(IngredientRecipe::class);
}
Was versuche ich zu tun:
Auf meiner Benutzerprofilseite möchte ich eine Liste von Rezepten für den Eigentümer (Benutzer) anzeigen. Jedes Rezept enthält Inhaltsstoffe () , die in Pivot -Tabelle mit Additionall -Spaltenmengen sind.

Code: Select all

    public function show_profile(User $user)
{
$userRecipes = $user->recipes()->with('ingredients', 'guideSteps')->get();

return view('user.user-profile', compact('user', 'userRecipes'));
}
Problem:
Laravel weiß nicht, dass Pivot-> Unit_id mit dem Einheitsmodell zusammenhängt. Abfragen :
Wählen Sie * von Benutzern wobei Benutzer .

Code: Select all

id
= 1 limit 1
Wählen Sie * aus Einheiten wobei Einheiten .

Code: Select all

id
= 3 limit 1
Wählen Sie * aus Einheiten wobei Einheiten .

Code: Select all

id
= 3 limit 1
... 12 More
Und ein Problem ist an diesem Ort:

Code: Select all

@foreach($userRecipes as $recipe)

@endforeach

---------------inside component recipe-card:------------------------

@foreach($recipe->ingredients as $ingredient)

{{ $ingredient->name }}

{{ $ingredient->pivot->quantity . ' '. $ingredient->pivot->unit->name}}

@endforeach

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post