Laravel升序记录显示

huangapple go评论50阅读模式
英文:

Laravel Ascending order records display

问题

I'm creating a Laravel project. I have retrieved the data from the database and I am viewing it in JSON format in ascending order. I tried the example, but it's not working. What I have tried so far is attached below.

$keyword = $request->get('search');
$perPage = 25;

if (!empty($keyword)) {
    $courses = Course::where('name', 'LIKE', "%$keyword%")
        ->paginate($perPage);
} else {
    $courses = Course::paginate($perPage);
}

return response()->json($courses)->orderBy('id', 'asc')->get();
英文:

I'm creating a Laravel project. I have retrieved the data from the database and I am viewing it in JSON format in ascending order. I tried the example, but it's not working. What I have tried so far is attached below.

$keyword = $request->get('search');
$perPage = 25;

if (!empty($keyword)) {
    $courses = Course::where('name', 'LIKE', "%$keyword%")
        ->all()->paginate($perPage);
} else {
    $courses = Course::all()->paginate($perPage);
}

return response()->json($courses)->orderBy('id', 'asc')->get();

答案1

得分: 1

你不能在非 Eloquent 类中使用 orderBy。而是在 Eloquent 构建器上使用它。

当一个 Eloquent 构建器调用 all() 后,它不再是 Eloquent,而变成了集合。

尝试这样做:

$perPage = 25;
$courses = Course::query();
if ($request->has('search')) {
   $courses->where('name', 'LIKE', "%" . $request->get('search') . "%");      
}
$courses->orderBy('id', 'asc');
$paginatedCourses = $courses->paginate($perPage);
return response()->json($paginatedCourses);
英文:

You cannot use orderBy in not Eloquent Class. Instead, use it on Eloquent Builder.

When an eloquent builder call all() is not eloquent anymore, it is become Collection.

Try this:

$perPage = 25;
$courses = Course::query();
if ($request->has('search')) {
   $courses->where('name', 'LIKE', "%" . $request->get('search') . "%");      
}
$courses->orderBy('id', 'asc');
$paginatedCourses = $courses->paginate($perPage);
return response()->json($paginatedCourses);

答案2

得分: 1

你可以使用查询中的 orderBy,而不是像文档中那样在之后使用。并且 all() 会返回所有结果

$keyword = $request->get('search');
$perPage = 25;

$query = Course::query();

if (!empty($keyword)) {
    $query->where('name', 'LIKE', "%$keyword%");
}

$courses = $query->orderBy('id', 'asc')->paginate($perPage);

return response()->json($courses);
英文:

You can orderBy with the query, not after like the docs. And all() will return all results.

$keyword = $request->get('search');
$perPage = 25;

$query = Course::query();

if (!empty($keyword)) {
    $query->where('name', 'LIKE', "%$keyword%");
}

$courses = $query->orderBy('id', 'asc')->paginate($perPage);

return response()->json($courses);

答案3

得分: 1

为什么后来才排序?为什么不在查询之前使用数据库引擎执行排序?

这里你告诉 Laravel "将其转换为 JSON 文本",然后你想告诉文本"按照 ID 列排序",但现在我们不再讨论数组和对象,而是文本,所以你的请求没有意义。

response()->json($courses)->orderBy('id', 'asc')->get()

解决方案

$keyword = $request->get('search');
$perPage = 25;

if (!empty($keyword)) {
    $courses = Course::where('name', 'LIKE', "%$keyword%")
        ->orderBy('id', 'asc')
        ->paginate($perPage); // 不需要 ->all()
} else {
    $courses = Course::orderBy('id', 'asc')
        ->paginate($perPage); // 不需要 ->all()
}

return response()->json($courses); // 不需要 ->get()

更简洁、考虑周到的编码

$keyword = $request->get('search');
$perPage = 25;

// 这只是一个尚未执行的查询
// 我们只是在构建它以指定我们想要的内容。查询将在调用以下函数之一时执行:->first()、->get()、->all() 或 ->paginate()
$courses = Course::orderBy('id', 'asc');

if (!empty($keyword)) {
    // 查询仍未执行;我们只是添加了一个条件
    $courses = $courses->where('name', 'LIKE', "%$keyword%");
}

// 查询在这里使用 ->paginate() 执行,然后我们使用 response()->json() 返回响应
return response()->json($courses->paginate($perPage));

总结

构建查询

首先,我们需要组装我们要查询的内容。为此,我们可以使用诸如 ->where()->orderBy()->groupBy() 等函数。您可以使用任何需要的逻辑链接它们在一起。

获取结果

构建了这个逻辑后,您可以使用 ->first()->get()->all()->paginate() 函数检索符合条件的记录。这将根据使用的函数返回对象或数组。(这已经足够好了。)

all() 还是 get()?

all() 方法将所有查询结果作为集合返回,而 get() 方法仅将结果作为简单的数组返回。因此,all() 方法无法直接影响或筛选 它只能在检索记录后筛选已检索的记录。这通常会带来问题。想象一个包含 10,000 行的表,在获取所有 10,000 行后筛选出奇数 ID 的行,结果为 5,000 条记录。相比之下,使用 get() 方法进行预筛选,数据库将执行筛选,服务器只会收到 5,000 条记录,而不是全部的 10,000 条。

在我看来,all() 方法在极少数情况下可能有用。数据库引擎能够以出色的性能执行筛选和分组操作,使 get() 成为一个非常实用的替代方法。 在列出或导出所有数据的情况下,all() 方法可能提供一些优势,但即使在这些情况下,它的用处也有限。你使用的 paginate() 方法是避免一次性处理所有记录的好方法。

始终重要的是,尽可能只查询必要的记录,并最小化执行的查询次数。

用响应发送

之后,您可以使用 ->json() 将数组/对象转换为 JSON 格式,如果要将其传输到客户端的话。

英文:

Why do you sort afterwards? Why don't you perform the sorting with the database engine before the query?

Here you're telling Laravel to "convert it to JSON text", and then you want to tell the text to "sort by the ID column", but now we're no longer talking about arrays and objects, but rather about text, so your request doesn't make sense.

response()->json($courses)->orderBy('id', 'asc')->get()

Solution

$keyword = $request->get('search');
$perPage = 25;

if (!empty($keyword)) {
    $courses = Course::where('name', 'LIKE', "%$keyword%")
        ->orderBy('id', 'asc')
        ->paginate($perPage); // don't need ->all()
} else {
    $courses = Course::orderBy('id', 'asc')
        ->paginate($perPage); // don't need ->all()

}

return response()->json($courses); // don't need ->get()

More concise, thoughtful coding

$keyword = $request->get('search');
$perPage = 25;

// It's a query that hasn't been executed yet
// We're just building it to specify what we want. The query will be executed when one of the following functions is called: ->first(), ->get(), ->all(), or ->paginate()
$courses = Course::orderBy('id', 'asc');

if (!empty($keyword)) {
    // The query has still not been executed; we have just added a condition to it
    $courses = $courses->where('name', 'LIKE', "%$keyword%");
}

// The query was executed here using ->paginate(), and then we returned the response using response()->json()
return response()->json($courses->paginate($perPage));

Summary

Build Query

Firstly, we need to assemble what we want to query. For this, we can use functions like ->where(), ->orderBy(), ->groupBy(), etc. You can chain them together with any logic you need.

Get Result

Once this logic is built, you can retrieve the records that match the conditions using the ->first(), ->get(), ->all(), or ->paginate() functions. This will give you an object or an array, depending on the function used. (This is already good on its own.)

all() or get()?

The all() method returns all query results as a collection, while the get() method only returns the results as a simple array. Therefore, the all() method cannot have any direct influence or filtering applied It can only filter the already retrieved records afterwards. This can often be problematic. Imagine a table with 10,000 rows, where you fetch all 10,000 rows and then filter out the ones with odd IDs, resulting in 5,000 records. In contrast, using pre-filtering with the get() method, the database would have performed the filtering, and the server would only receive 5,000 records instead of the full 10,000.

In my opinion, the all() method can be useful in very rare cases. Database engines are capable of performing filtering and grouping operations with excellent performance, making get() a very practical alternative. The all() method may provide some advantages when listing or exporting all data, but even in those cases, its usefulness is limited. The paginate() method you used is a great way to avoid working with all records at once.

It's always important to make sure that whenever possible, we only query the necessary records and minimize the number of queries executed.

Send with response

After that, you can transform the array/object into JSON format using ->json() if you want to transmit it to the client side.

huangapple
  • 本文由 发表于 2023年6月15日 15:59:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76480315.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定