Laravel Advanced何处将变量传递给函数? [英] Laravel Advanced Wheres how to pass variable into function?
问题描述
文档中的示例
DB::table('users')
->whereExists(function($query)
{
$query->select(DB::raw(1))
->from('orders')
->whereRaw('orders.user_id = users.id');
})
->get();
但是如果我需要使用这样的外部变量怎么办?
But what if I need to use external variable like that:
->where('city_id', '=', $this->city->id)
->where(function($query)
{
$query->where('name', 'LIKE', '%'.$searchQuery.'%')
->orWhere('address', 'LIKE', '%'.$searchQuery.'%')
})
目前,我创建了新属性并通过$this->
访问了它,但是还有其他更便捷的方法吗?
For now I created new property and accessed it through $this->
, but is there any more convenient way?
推荐答案
您可以使用use
关键字将必要的变量从父范围传递到闭包中.
You can pass the necessary variables from the parent scope into the closure with the use
keyword.
例如:
DB::table('users')->where(function ($query) use ($activated) {
$query->where('activated', '=', $activated);
})->get();
有关此处的更多信息.
PHP 7.4(将在 2019年11月28日发布)引入了一个较短的变体称为箭头功能的匿名函数,这使它的详细程度降低了.
PHP 7.4 (will be released at November 28, 2019) introduces a shorter variation of the anonymous functions called arrow functions which makes this a bit less verbose.
使用PHP 7.4的示例,在功能上几乎等效(请参见下面的第3个要点):
An example using PHP 7.4 which is functionally nearly equivalent (see the 3rd bullet point below):
DB::table('users')->where(fn($query) => $query->where('activated', '=', $activated))->get();
与常规语法相比的差异:
Differences compared to the regular syntax:
-
fn
关键字而不是function
. - 无需显式列出应从父级作用域捕获的所有变量-现在这是自动按值完成的.请参阅后面的示例中缺少
use
关键字的内容. - 箭头功能始终返回一个值.这也意味着在声明它们时不可能使用
void
返回类型. - 必须省略
return
关键字 . - 箭头功能必须具有单个表达式,即return语句.目前不支持多行功能.您仍然可以链接方法.
fn
keyword instead offunction
.- No need to explicitly list all variables which should be captured from the parent scope - this is now done automatically by-value. See the lack of
use
keyword in the latter example. - Arrow functions always return a value. This also means that it's impossible to use
void
return type when declaring them. - The
return
keyword must be omitted. - Arrow functions must have a single expression which is the return statement. Multi-line functions aren't supported at the moment. You can still chain methods though.
这篇关于Laravel Advanced何处将变量传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!