dongpan9760 2017-12-05 15:56
浏览 824
已采纳

Laravel按自定义日期字段排序

laravel orderBy id works fine with this function:

News::orderBy('id', 'desc')->paginate(20);

But I'm struggling to achieve this with a custom field.

My custom date field (sorting) is a jQuery UI datepicker field that fills a chosen date and it's in this format:

yy-mm-dd

so, if I choose from the datepicker let's say today it will be displayed as a 2017-12-05 and that saves in the database in a same format.

The reason for using this custom field is to add a old news articles, but in a different order.

I've tried to do this with:

News::orderBy('sorting', 'desc')->paginate(20);

but this error is displayed:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sorting' in 'order clause' (SQL: select * from `news` order by `sorting` desc limit 20 offset 0)

That column does exists in my database.

How can I order my created articles using my custom "sorting" date field in Laravel?

EDIT:

This is the function for the news lists:

public function newsList() {
        $news = News::orderBy('id', 'desc')->paginate(20);
        return view('news-list', compact('news'));
    }

As I mention before this works, but the idea is to order by a custom date field.

  • 写回答

1条回答 默认 最新

  • doutanghuan9595 2017-12-06 09:18
    关注

    OK, guys I've found the problem! :)

    I'll post it here, so it might be useful for someone else.

    I'm using the Laravel Translatable plugin. It has two models and two database for the articles. For an example "news" and "newsTranslation".

    So, when I want to use orderBy, I cannot order by fields records from the "newsTranslation". That will be only possible from the "news" table.

    This error was displayed

    SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sorting' in 'order clause' (SQL: select * from `news` order by `sorting` desc limit 20 offset 0)
    

    because the orderBy is trying to order the articles from the "news", not the "newsTranslation" and in my case that field wasn't available in the "news" table.

    I've fix that by creating a date custom field in the "news". Now everything works fine.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 视频编码 十六进制问题
  • ¥15 Xsheii7我安装这个文件的时候跳出来另一个文件已锁定文件的无一部分进程无法访问。这个该怎么解决
  • ¥15 unity terrain打包后地形错位,跟建筑不在同一个位置,怎么办
  • ¥15 FileNotFoundError 解决方案
  • ¥15 uniapp实现如下图的图表功能
  • ¥15 u-subsection如何修改相邻两个节点样式
  • ¥30 vs2010开发 WFP(windows filtering platform)
  • ¥15 服务端控制goose报文控制块的发布问题
  • ¥15 学习指导与未来导向啊
  • ¥15 求多普勒频移瞬时表达式