php - 选择空 "where"的查询。十月CMS

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

}

如何修复它?

最佳答案

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

关于php - 选择空 "where"的查询。十月CMS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50181790/

相关文章:

php - 十月 CMS : How to extend the backend user with role scope

php - Laravel模型对象检索关系模型与where条件没有 "get"方法

PHP 在没有 session 的情况下存储用户数据

php - 按类别(术语)过滤 WooCommerce $order 商品

php - 如何使用 FFmpeg 旋转视频?

PHP 日期让我很沮丧

mysql - 将数据从 Google Spreadsheets 导入 MySQL

mysql - 如何在mariadb/mysql中解释语法错误1064

php - 多次上传未保存到数据库

laravel - 播种或迁移表时,如何向控制台提供输出?