数据库查询,如何传递参数给 where() 方法中的闭包函数呢?

我有段 SQL 查询语句是这样的:

$notes = DB::select('select * from notes 
where owner = ? 
and isDeleted = ? 
and (title like ? or content like ? or summary like ?)', [
    $this->getUserId(),
    0,
    $find,
    $find,
    $find
]);

我想把它转换成这种形式:

$notes = DB::table('notes')
    ->where('owner', $this->getUserId())
    ->where('isDeleted', 0)
    ->where(function($query) {
        $query->where('title', 'like', $find)
            ->orwhere('content', 'like', $find)
            ->orwhere('summary', 'like', $find);
    })
    ->get();

但是这样写的话,闭包函数里的变量 $find 要怎样传递进去呢?
我在网上搜索了很多例子,都没有讲到这个传递参数的问题,在网络上的很多例子中,闭包函数中都没有用到变量。
我试过这样写:

$notes = DB::table('notes')
    ->where('owner', $this->getUserId())
    ->where('isDeleted', 0)
    ->where(function($query, $find) {
        $query->where('title', 'like', $find)
            ->orwhere('content', 'like', $find)
            ->orwhere('summary', 'like', $find);
    })
    ->get();

但是这样的话,会提示闭包函数指定了两个参数,实际上却只提供了一个参数。

《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
最佳答案

找到解决办法了:

$notes = DB::table('notes')
    ->where('owner', $this->getUserId())
    ->where('isDeleted', 0)
    ->where(function($query) use($find) {
        $query->where('title', 'like', $find)
            ->orwhere('content', 'like', $find)
            ->orwhere('summary', 'like', $find);
    })
    ->get();

参考资料:blog.csdn.net/patrick75/article/de...

我搜英文资料搜了半天没搜到,没想到搜中文资料搜出来了 :sweat_smile::sweat_smile::sweat_smile:

话说 laravel 文档里好像没有提到这个 use() 的用法啊……

2年前 评论
clark 2年前
乘风追月 (作者) (楼主) 2年前
讨论数量: 6

找到解决办法了:

$notes = DB::table('notes')
    ->where('owner', $this->getUserId())
    ->where('isDeleted', 0)
    ->where(function($query) use($find) {
        $query->where('title', 'like', $find)
            ->orwhere('content', 'like', $find)
            ->orwhere('summary', 'like', $find);
    })
    ->get();

参考资料:blog.csdn.net/patrick75/article/de...

我搜英文资料搜了半天没搜到,没想到搜中文资料搜出来了 :sweat_smile::sweat_smile::sweat_smile:

话说 laravel 文档里好像没有提到这个 use() 的用法啊……

2年前 评论
clark 2年前
乘风追月 (作者) (楼主) 2年前

基础语法 use

2年前 评论
putyy (作者) 2年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!