通过 URL 将多个列传递给 orderBy 方法

Pass several columns to an orderBy method via URL

我在 Lumen 5.6(Laravel 微框架)中有这段代码,我想为多个列使用 orderBy 方法,例如,http://apisurl/books?orderBy=devices,name,restrictions,category 也发送 asc 或 desc 顺序。

Lumen 的文档说我们可以像这样使用 orderBy

$books = PartnersBooks::all()->orderBy('device', 'asc')->orderBy('restrictions', 'asc')->get();

因此,我创建了一个带有 foreach 的函数来填充具有不同 orderBy 请求值的数组,并尝试进行 eloquent 查询但没有成功。

有人能帮帮我吗?

use Illuminate\Http\Request;

public function index(Request $request)
{
    $limit = $request->input('limit');

    $books = PartnersBooks::where('is_direct', '=', 1)
      ->with('direct')
      ->whereHas('direct', function ($query) {
          $query->enable()
            ->select(['id', 'book_id', 'name', 'devices', 'flow', 'restrictions', 'countries', 'targeting']);
      })
      ->orderBy('id', 'asc')
      ->paginate($limit, ['id', 'category', 'description']);

     $status = !is_null($books) ? 200 : 204;
     return response()->json($books, $status);
}

你可以这样做:

// Get order by input
$orderByInput = $request->input('orderBy');
// If it's not empty explode by ',' to get them in an array, 
// otherwise make an empty array
$orderByParams = !empty($orderByInput) 
    ? explode(',', $orderByInput)
    : [];

$query = PartnersBooks::where('is_direct', '=', 1)
    ->with('direct')
    ->whereHas('direct', function ($query) {
      $query->enable()
        ->select(['id', 'book_id', 'name', 'devices', 'flow', 'restrictions', 'countries', 'targeting']);
    });

// Foreach over the parameters and dynamically add an orderBy
// to the query for each parameter
foreach ($orderByParams as $param) {
    $query = $query->orderBy($param);
}

// End the query and get the results
$result = $query->paginate($limit);