выберите запрос с пустым «где». octobercms - PullRequest
0 голосов
/ 04 мая 2018

Я использую код для фильтрации через $ _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= возврат пустой строки

Теперь я использую что-то подобное

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 голосов
/ 04 мая 2018

Я не знаю 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 может быть достаточно, в зависимости от того, как этот объект работает внутри.

...