选择带有空“where”的查询十月

qncylg1j  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(333)

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

}

我该怎么修?

v1l68za4

v1l68za41#

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

相关问题