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 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器