本文介绍了Laravel API:如何仅获取一些字段并对响应进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道我是否做对了.

I would like to know if I do the things correctly.

比方说,我有一个表格国家".为了以某种顺序仅获取此表的某些字段,我有以下网址:

Let's say I have a table "countries". To get only some fields of this table, in a certain order, I have this url :

/countries?fields = id,country_name& desc = country_name

结果很明显:

[
    {
        "id": "SP",
        "country_name": "Spain"
    },
    {
        "id": "IT",
        "country_name": "Italy"
    },
    {
        "id": "FR",
        "country_name": "France"
    },
    {
        "id": "CN",
        "country_name": "China"
    } ]

为此,我有这条路线:

Route :: get('/countries','CountryController @ index');

方法索引为:

public function index(Request $request)
{

    $query = Country::query();

    if ($request->has('fields')){         
        $fields = explode(',', $request->input('fields') );          
        foreach ($fields as $field) {
            $query->addSelect($field);
        }        
    }

    if ($request->has('sort')){
        $query->orderBy($request->input('sort'));
    }

    if ($request->has('desc')){
        $query->orderBy($request->input('desc'), 'desc');
    }

    $countries = $query->get();

    return response()->json($countries, 200);
}

工作正常.

我的问题仅仅是:我做对了吗?还有其他方法吗?

My question is only : does i do the things correctly ? Is there any other methods ?

非常感谢您的反馈.谢谢

thanks a lot for your feedback. Merci

Dom

推荐答案

为防止未知列异常,请尝试以下操作:

To prevent unknown column exception try this:

  1. 导入架构类use Illuminate\Support\Facades\Schema;
  2. 添加此内容:

  1. import Schema class use Illuminate\Support\Facades\Schema;
  2. add this:

$table = "countries";
if ($request->has('fields')){
    $fields = explode(',', $request->input('fields') );
    foreach ($fields as $field) {
        if(!Schema::hasColumn($table,$field)){
            return response("Unknown field", 422);
        }
        $query->addSelect($field);
    }
}

这篇关于Laravel API:如何仅获取一些字段并对响应进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 02:31