查询时怎么根据一个变量有没有值来判断条件?

我学 laravel 没多久,之前一直在看文档,最近才练习上手,但是碰上一个查询的问题,望各位解答一下。
首先我先说一下我目前的情况:一个商品列表,有 2 种条件,种类和关键字,现在我在展示列表的时候需要根据有没有条件做限制,但在 laravel 下不清楚这个需求用 Eloquent 怎么实现,先拿简单代码为例

//种类为0时就不限制种类
$type=$_GET['type']?$_GET['type']:'0';
$key=$_GET['key']?$_GET['key']:'';
if($type){
    $where_type='`type`='.$type;
}else{
    $where_type='1=1';
}
//关键词key既可用来搜索名称也可以用来搜索商品编号
if($key){
    $where_key='`g_name` like %'.$key.'% or `g_goodsnum` like %'.$key;
}else{
    $where_key='1=1';
}

select * from goods where $where_type and ($where_key);
//如果种类和关键词都有值的话,最后执行的sql语句是这样的
select * from goods where `type`=1 and (`g_name` like %3213% or g_goodsnum like %3213);

以上基本查询语句差不多就能实现需求,但是不清楚用 Eloquent 怎么实现,想用 where 条件闭包,但是里面不能写条件变量,也不能写第二个参数接值,目前写的代码是这样的(至于操作数据库代码在控制器层写的问题请先跳过不要深究~)

    /*
     * 商品列表页面
     */
    public function goodslist(Request $request){
        $wheretype=$request->input('type','0');
        if($wheretype=='0'){
            $where_type1='like';
            $where_type2='%%';
        }else{
            $where_type1='=';
            $where_type2=$wheretype;
        }
        $model_goods=new Goods();
        $count=$model_goods->where('tid',$where_type1,$where_type2)->where(function($query,Request $request){
            $wherekey=$request->input('wherekey','');
            $query->where('g_name','like','%'.$wherekey.'%')->orWhere('g_goodsnum','like','%'.$wherekey);
        })->count();
    }

希望帮忙解决!

《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
最佳答案

可以使用 eloquent 的 when 语句进行判断,

$results =  (new Goods())
    ->when($request->has('type'), function($query) use ($request){
        // todo logic
    })
    ->when(!$request->has('type'), function($query) use ($request){
        // todo logic
    })
    ->other query builder.....
    ->get();

需要注意的是 when 语句是 L5.2.27 以后才引入 eloquent 的。

8年前 评论
讨论数量: 7

使用 scope 變得更為優雅

閉包要使用 use 導入 $request 這個變數

去看看官方的文檔吧

8年前 评论

可以使用 eloquent 的 when 语句进行判断,

$results =  (new Goods())
    ->when($request->has('type'), function($query) use ($request){
        // todo logic
    })
    ->when(!$request->has('type'), function($query) use ($request){
        // todo logic
    })
    ->other query builder.....
    ->get();

需要注意的是 when 语句是 L5.2.27 以后才引入 eloquent 的。

8年前 评论

@jl9404 查询作用域么?找到了,我看看文档,不过你说的闭包要使用 use 导入 $request ,我在控制器上面已经写了

use Illuminate\Http\Request;

在闭包里还是用不了,报这个错误:

Type error: Argument 2 passed to App\Http\Controllers\IndexController::App\Http\Controllers{closure}() must be an instance of Illuminate\Http\Request, none given

8年前 评论

@young 哇哦~多谢多谢,我看文档太马虎了,还要多看几遍啊,哈哈:sweat_smile:

8年前 评论
Summer

@lyfireworks07 请注意排版,尤其是代码块

8年前 评论

@jl9404 额,知道 use $request 什么意思了,多谢指点,一下知道了两种用法,哈哈

8年前 评论