【问题标题】:Adding a column to a table exists in the database and fill it without adding it in the database向表中添加列在数据库中存在并填充它而不将其添加到数据库中
【发布时间】:2021-08-07 04:22:30
【问题描述】:

我在 laravel 8 中有一个查询,我想根据我想从其他列的值计算的值对结果进行排序......就像这样:

$fromDB = User::where('Title', 'like', $string)
        ->orderBy('length', 'asc')

其中长度不是用户表中的列,但我想将其作为列而不将其添加到表本身,并且我想用每条记录的 $string 长度填充它

提前致谢

【问题讨论】:

  • 查询排序后可以使用sortBy()SortByDesc() 方法执行
  • 我想根据标题的长度对模型进行排序,那么如何在查询结束后将每条记录的标题长度带入?有什么想法吗????
  • sortByDesc 会帮你看看我对结果的回答

标签: laravel


【解决方案1】:

要在查询排序后执行,使用sortBy() 升序或sortByDesc() 降序,类似于下面的代码

$users = User::where('Title', 'like', $string);
$sortedUsers = $users->sortByDesc(function ($user, $key) {
     return strlen($user->title);
});

更多:https://laravel.com/docs/8.x/collections#method-sortby

【讨论】:

    猜你喜欢
    • 2021-07-06
    • 2020-07-30
    • 2014-08-21
    • 1970-01-01
    • 2013-08-20
    • 2020-09-30
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多