【问题标题】:select query with empty "where". octobercms选择带有空“where”的查询。十月cms
【发布时间】:2018-05-04 19:18:44
【问题描述】:

我使用代码通过 $_GET 进行过滤

    $this['painting'] = Painting::
    where('p_price',$p_price)->
    where('p_created',$p_created)   ->
    where('type_id',$type_id)   ->
    whereHas('artist', function($q)
        {
             $q->where('artist_slug', '=', $this->param('slug'));
        })->get();

网址是mysite/page.php?type_id=3&p_created=1996 一切正常。

但是如果我有一些空的参数我没有结果。例如 url 是 mysite/page.php?type_id=&p_created=1996 或 url 是 mysite/page.php?type_id=3&p_created=return 空字符串

现在我使用类似的东西

if (!$p_created and !$type_id){
    $this['painting'] = Painting::
    whereHas('artist', function($q)
        {
             $q->where('artist_slug', '=', $this->param('slug'));
        })->get();
}
elseif (!$p_created and $type_id){
        $this['painting'] = Painting::
        where('type_id',$type_id)   ->
        whereHas('artist', function($q)
        {
             $q->where('artist_slug', '=', $this->param('slug'));
        })->get();
}
elseif ($p_created and !$type_id){
        $this['painting'] = Painting::
        where('p_created',$p_created)   ->
        whereHas('artist', function($q)
        {
             $q->where('artist_slug', '=', $this->param('slug'));
        })->get();
}
    elseif ($p_created and $type_id){
        $this['painting'] = Painting::
    where('p_created',$p_created)   ->
    where('type_id',$type_id)   ->
    whereHas('artist', function($q)
        {
             $q->where('artist_slug', '=', $this->param('slug'));
        })->get();

}

我该如何解决?

【问题讨论】:

    标签: php mysql octobercms


    【解决方案1】:

    我不了解OctoberCMS,也看不到获得基本查询对象的明显方法,但您可以通过执行始终返回true 的查询来模拟这一点。像这样的:

    // Assuming type_id is always a positive integer, no nulls allowed
    $this['painting'] = Painting::where('type_id', '>', -1);
    

    然后添加每个条件(如果存在):

    if ($this->param('slug')){
        $this['painting'] = $this['painting']->
            whereHas('artist', function($q){
                 $q->where('artist_slug', '=', $this->param('slug'));
            });
    }
    if ($p_created){
        $this['painting'] = $this['painting']->
            where('p_created',$p_created);
    }
    if ($type_id){
        $this['painting'] = $this['painting']->
            where('type_id',$type_id);
    }
    

    最后,得到结果:

    $this['painting'] = $this['painting']->get();
    

    很多人不需要总是使用$this['painting'] = $this['painting']->where,只需$this['painting']->where 就足够了,具体取决于该对象在内部的工作方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      • 2017-05-31
      相关资源
      最近更新 更多