Laravel API APP 多对多关系,如何在JSON中返回具体信息? [英] Laravel API APP Many-Many Relationship, how to return specific information in JSON?
问题描述
我已经尝试解决这个问题有一段时间了.基本上,我有 2 个模型Recipe"、Ingredient"和一个控制器RecipeController".我正在使用 Postman 来测试我的 API.当我转到使用 RecipeController@getRecipe 的获取路线时,返回值如下图所示:
I been trying to figure this out for some time now. Basically i got 2 models ' Recipe ', ' Ingredient ' and one Controller ' RecipeController ' . I'm using Postman to test my API. When i go to my get route which uses RecipeController@getRecipe, the return value is as per the pic below:
如果我希望获取路由的返回值采用下图的格式,我该如何实现?我的意思是我不想看到配方:created_at 列、updated_at 列和成分:数据透视信息列,只需要名称和数量列信息.
If i want the return value of the get route to be in the FORMAT of the below pic, how do i achieve this? By this i mean i don't want to see for the recipes: the created_at column, updated_at column and for ingredients: the pivot information column, only want name and amount column information.
配方模型:
<?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'));
}
}
成分模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Ingredient extends Model
{
protected $fillable = ['name', 'amount'];
}
食谱控制器
<?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 路由:
Route::post('/recipe', 'RecipeController@postRecipe')->name('get_recipe');
Route::get('/recipe', 'RecipeController@getRecipe')->name('post_recipe');
谢谢各位!
推荐答案
我认为您最好的解决方案是使用 Transformer.使用您当前的实现,我建议只获取循环中所需的字段,即:
I think your best solution is using Transformer. Using your current implementation what I would recommend is fetching only the needed field in your loop, i.e:
foreach ($recipes as $recipe) {
$recipe = $recipe->ingredients->only(['ingredient_name', 'ingredient_amount']);
}
虽然上述可能可行,但您当前的实现存在问题,因为会有大量迭代/循环轮询数据库,我建议改为预先加载关系.但是对于这个问题,您只需要Transformer.
While the above might work, yet there is an issue with your current implementation because there will be tons of iteration/loop polling the database, I would recommend eager loading the relation instead. But for the sake of this question, you only need Transformer.
使用composer安装transformer composer require League/fractal
然后就可以在app
目录下创建一个名为Transformers
的目录.
Install transformer using composer composer require league/fractal
Then you can create a directory called Transformers
under the app
directory.
然后创建一个名为 RecipesTransformer 的类,并初始化为:
Then create a class called RecipesTransformer, and initialize with:
namespace App\Transformers;
use App\Recipe;
use League\Fractal\TransformerAbstract;
class RecipesTransformer extends TransformerAbstract
{
public function transform(Recipe $recipe)
{
return [
'name' => $recipe->name,
'description' => $recipe->description,
'ingredients' =>
$recipe->ingredients->get(['ingredient_name', 'ingredient_amount'])->toArray()
];
}
}
然后你可以像这样在你的控制器方法中使用这个转换器:
Then you can use this transformer in your controller method like this:
use App\Transformers\RecipesTransformer;
......
public function getRecipe()
{
return $this->collection(Recipe::all(), new RecipesTransformer);
//or if you need to get one
return $this->item(Recipe::first(), new RecipesTransformer);
}
可以参考一个很好的教程like此获取更多灵感,或直接访问Fractal 的页面了解详情.
You can refer to a good tutorial like this for more inspiration, or simply go to Fractal's page for details.
更新
为了使 Fractal 集合工作,因为如果您的项目中有 Dingo API,我给出的示例将起作用,您可以通过以下方式手动创建它:
In order to get Fractal collection working since the example I gave would work if you have Dingo API in your project, you can manually create it this way:
public function getRecipe()
{
$fractal = app()->make('League\Fractal\Manager');
$resource = new \League\Fractal\Resource\Collection(Recipe::all(), new RecipesTransformer);
return response()->json(
$fractal->createData($resource)->toArray());
}
如果你想制作一个物品而不是收藏品,那么你可以用 new \League\Fractal\Resource\Item
代替.我建议您安装 Dingo API,或者您可以关注 this简单的教程为了有更多的处理工整,没有不必要的重复
In case you want to make an Item instead of collection, then you can have new \League\Fractal\Resource\Item
instead. I would recommend you either have Dingo API installed or you can follow this simple tutorial in order to have in more handled neatly without unnecessary repeatition
这篇关于Laravel API APP 多对多关系,如何在JSON中返回具体信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!