【问题标题】:silverstripe query does not work, best way to debug?silverstripe 查询不起作用,最好的调试方法是什么?
【发布时间】:2015-05-29 07:37:24
【问题描述】:

我的 silverstripe 查询不起作用(它输出所有消息,而不是日期范围内的消息)

解决此查询的最佳方法是什么? 我对 silverstripe 还很陌生,还没有找到有关如何打印原始查询的信息。

return = Message::get()
            ->filter(array(
                'IsPublished' => true,
                'StartPublication:LessThanOrEqual' => date('Y-m-d'),
                'Priority' => array('High', 'Normal')
            ))
            ->where("\"StopPublication\" >= ".date('Y-m-d')." OR \"StopPublication\" IS NULL")
            ->sort('StartPublication', 'DESC')->limit($this->getLimit());

【问题讨论】:

    标签: sql silverstripe datalist


    【解决方案1】:

    正确的答案是不要使用 where()——这是很多学习者陷入的陷阱方法(大概是因为名字的原因)。它基本上只适用于 ORM 无法处理的非常复杂的事情。

    您至少在调用过滤器,这是正确的。但是你想要的而不是 where() 是 filterAny():

    Message::get()
        ->filter([
            'IsPublished' => true,
            'StartPublication:LessThanOrEqual' => 'now',
            'Priority' => ['High', 'Normal']
        ])
        ->filterAny([
            'StopPublication:GreaterThanOrEqual' => 'now',
            'StopPublication' => null
        ])
        ->sort('StartPublication', 'DESC')
        ->limit($this->getLimit());
    

    正如另一个答案已经指定的那样,不要在 return 上使用 = (或在 return 前放一个 $ 以使其成为变量),并返回查询本身使用 $datalist->sql() http://api.silverstripe.org/3.1/class-DataList.html#_sql

    但是 - 查看有关 SQLQuery 的文档是错误的,因为您没有使用 SQLQuery。您正在使用 ORM,因此此文档页面更相关:http://docs.silverstripe.org/en/3.1/developer_guides/model/data_model_and_orm/#filterany

    【讨论】:

      【解决方案2】:

      对于开始 return = Message::get() 它只是 return Message::get()

      我假设你已经设置了 php 错误报告以便它输出错误并且 SS 也处于开发模式所以它不会隐藏错误输出。

      您的问题的答案是:

      将其输出到输出 html:

      Debug::dump(Message::get()
                  ->filter(array(
                      'IsPublished' => true,
                      'StartPublication:LessThanOrEqual' => date('Y-m-d'),
                      'Priority' => array('High', 'Normal')
                  ))
                  ->where("\"StopPublication\" >= ".date('Y-m-d')." OR \"StopPublication\" IS NULL")
                  ->sort('StartPublication', 'DESC')->limit($this->getLimit())->sql());
      

      或输出到项目根日志文件

      Debug::log(Message::get()
                  ->filter(array(
                      'IsPublished' => true,
                      'StartPublication:LessThanOrEqual' => date('Y-m-d'),
                      'Priority' => array('High', 'Normal')
                  ))
                  ->where("\"StopPublication\" >= ".date('Y-m-d')." OR \"StopPublication\" IS NULL")
                  ->sort('StartPublication', 'DESC')->limit($this->getLimit())->sql());
      

      http://docs.silverstripe.org/en/developer_guides/model/sql_query/

      猜你喜欢
      • 1970-01-01
      • 2013-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 2019-12-19
      相关资源
      最近更新 更多