php - 选择带有空“where”的查询。十月cms
问题描述
我使用代码通过 $_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
可能就足够了,具体取决于该对象在内部的工作方式。
推荐阅读
- python - Tkinter 使网格适合框架大小
- vue.js - 当我使用 vueJS 循环时,我的轮播不工作
- python - 在 Mac 上加载模块 -Python3
- ios - 仅在某些特定的 ViewController 中启用横向
- web-scraping - 直接使用 POST 请求 URL 时不起作用
- java - 透明的 JButton 在单击时变为浅蓝色
- java - 从集合类获取同步集合是否会同步一个类?
- java - 由于 API 问题导致应用程序崩溃
- multithreading - 如何强制在 Swift 中更新 UI?
- java - 如何检查sqlite中是否存在记录,如果存在,则更新它。?