选择空的"其中"。 octobercms

时间:2018-05-04 19:18:44

标签: php mysql 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();

网址为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=,返回空字符串

现在我使用类似的东西

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

}

我该如何解决?

1 个答案:

答案 0 :(得分:0)

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