select 查询为空 "where"。十月公关

select query with empty "where". octobercms

我使用代码通过 $_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();

url 是 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();

}

我该如何解决?

我不了解 OctoberCMS,而且我没有看到一个明显的方法来获得一个基本的查询对象,但是你可以通过执行一个总是 return 为真的查询来模拟它。像这样:

// 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 就足够了,具体取决于该对象的内部工作方式。