gpt4 book ai didi

php - Laravel:在急切加载中将类函数作为回调传递?

转载 作者:行者123 更新时间:2023-12-04 12:45:26 25 4
gpt4 key购买 nike

我使用 constraint eager load使用匿名函数:

$users = App\User::with(['posts' => function ($query) {
$query->where('title', 'like', '%first%');
}])->get();

现在我想用类函数替换匿名函数。根据PHP: How to use a class function as a callback我找到了

A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.

因此我预计以下内容会起作用:

public function start()
{
$users = App\User::with(['posts' => [$this, 'addRestrain']])->get();
// ...
}

private function addRestrain($query)
{
$query->where('title', 'like', '%first%');
}

然而,Laravel 检测到传递的参数不是一个闭包,而是一个数组:

"Type error: Argument 3 passed to Illuminate\Database\Eloquent\Builder::eagerLoadRelation() must be an instance of Closure, array given, called in

这是否意味着不能将类函数用于预加载约束?

最佳答案

从 PHP 7.1.0 开始,您可以使用 Closure::fromCallable ( docs ):

$users = App\User::with(
[ 'posts' => \Closure::fromCallable([$this, 'addRestrain']) ]
)->get();

否则,您只能使用匿名函数包装 $this->addRestrain 调用。

关于php - Laravel:在急切加载中将类函数作为回调传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50353114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com