简体   繁体   English

Laravel Rest API - 获取 Z466DEEC76ECDF5FCA6D38571F6324D5Z4 中的特定列

[英]Laravel Rest API - Get specific columns in json

i'm building Restful API Using Laravel我正在使用 Laravel 构建 Restful API

what i wanna to do is to get specific columns in JSON response instead on get all column我想做的是获取 JSON 响应中的特定列,而不是获取所有列

For example I've Product Table with these columns例如我有这些列的产品表

title - price - description - status - created_at - updated at

and i just want to show title , price and description in JSON Response我只想在 JSON 响应中显示标题价格描述

So, any idea to do that?那么,有什么想法吗?

You can use select for certain field display:您可以使用select进行某些字段显示:

Model::select('title', 'price', 'description')->get();

Or, in get() method:或者,在get()方法中:

Model::get(['title', 'price', 'description']);

As you would like to make some typically visible attributes hidden on a given model instance, you may use the makeHidden method:由于您想在给定的 model 实例上隐藏一些通常可见的属性,您可以使用 makeHidden 方法:

$data = Model::all();
$data->makeHidden('price');

Now price will be hidden from your query.现在price将从您的查询中隐藏。

You can use map function after get() or all() method.您可以在 get() 或 all() 方法之后使用 map function 。

EX:前任:

Model::all()->map(function($product) {
    return [
        'title',
        'price',
        'description'
    ];
});

You can use a map only function which will give you the benefit that it also handles computed fields and not only "physical" SQL fields:您可以仅使用 map function ,这将为您带来好处,它还可以处理计算字段,而不仅仅是“物理” SQL 字段:

Model::get()->map->only([
      'title',
      'price',
      'description'
]);

The Answer from Abu Bin Oalid above does not work, it gives you just the attributes, and not the actual values.上面 Abu Bin Oalid 的答案不起作用,它只给你属性,而不是实际值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM