数据库查询,如何传递参数给 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();
但是这样的话,会提示闭包函数指定了两个参数,实际上却只提供了一个参数。
找到解决办法了:
参考资料:blog.csdn.net/patrick75/article/de...
我搜英文资料搜了半天没搜到,没想到搜中文资料搜出来了


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