Ich habe das schon seit einiger Zeit versucht herauszufinden. Im Grunde habe ich 2 Modelle 'Rezept', 'Zutat' und einen Controller 'RezeptController'. Ich benutze Postman, um meine API zu testen. Als ich zu meinem get Weg zu gehen, den RecipeController @ getRecipe verwendet, ist der Rückgabewert gemäß dem Bild unten:Laravel API APP viele-viele Beziehung, wie bestimmte Informationen in JSON zurückgegeben werden?
Wenn ich der Rückgabewert der Route planen, um in dem Format der unten will Bild, wie erreiche ich das? Damit meine ich, dass ich nicht nach den Rezepten sehen möchte: die Spalte created_at, die Spalte updated_at und für die Zutaten: die Pivot-Informationsspalte, nur die Spalteninformationen für Name und Menge.
Rezeptmodell:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Recipe extends Model
{
protected $fillable = ['name', 'description'];
public function ingredients()
{
return $this->belongsToMany(Ingredient::class,
'ingredient_recipes')->select(array('name', 'amount'));
}
}
Ingredient Modell:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Ingredient extends Model
{
protected $fillable = ['name', 'amount'];
}
RecipeController
<?php
namespace App\Http\Controllers;
use App\Ingredient;
use App\Recipe;
use Illuminate\Http\Request;
class RecipeController extends Controller {
public function postRecipe(Request $request)
{
$recipe = new Recipe();
$recipe->name = $request->input('name');
$recipe->description = $request->input('description');
$recipe->save();
$array_ingredients = $request->input('ingredients');
foreach ($array_ingredients as $array_ingredient) {
$ingredient = new Ingredient();
$ingredient->name = $array_ingredient['ingredient_name'];
$ingredient->amount = $array_ingredient['ingredient_amount'];
$ingredient->save();
$recipe->ingredients()->attach($ingredient->id);
}
return response()->json(['recipe' => $recipe . $ingredient], 201);
}
public function getRecipe()
{
$recipes = Recipe::all();
foreach ($recipes as $recipe) {
$recipe = $recipe->ingredients;
}
$response = [
'recipes' => $recipes
];
return response()->json($response, 200);
}
API Routes:
Route::post('/recipe', '[email protected]')->name('get_recipe');
Route::get('/recipe', '[email protected]')->name('post_recipe');
Danke Jungs!
Hey Omisakin, Danke für die Antwort. Ich habe Liga/Fraktal benötigt, habe die Klasse erstellt und die 'return $ this-> Sammlung implementiert (Recipe :: all(), new RecipesTransformer); 'in meine Steuerung @getRecipe. Das Problem, das ich jetzt bekomme, ist: 'Methode [Sammlung] existiert nicht. ". Die Methode 'Sammlung' wurde nicht im Rezept-Controller gefunden. –
Ich fügte ein Update zu der Antwort @JohnBiggs –
Thx wieder für die Antwort Omisakin. Ich werde in die Dingo API schauen, aber jetzt habe ich das Update auf meinem Controller implementiert und erhalte nun 'array_key_exists(): Das erste Argument sollte entweder eine Zeichenkette oder eine Ganzzahl sein.' ". Wie löse ich das? –