Laravel 条件 API 资源即使不需要也执行所有功能?

dr_*_*mio 0 laravel eloquent

所以我有一个 Laravel API 资源,它返回模型的标准数据库信息。但是,在某些情况下,我需要此资源来呈现一些触发复杂/缓慢查询的数据。

当我需要这些数据时,我不介意花费更长的时间,但由于大多数用例不需要它,所以我想使用$this->when()资源中的方法有条件地呈现它。

class SomeResource extends Resource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'created_at' => $this->created_at,

            //The "slow_query()" should not be executed
            'slow_result' =>  $this->when(false, $this->slow_query()),
        ];
    }
}
Run Code Online (Sandbox Code Playgroud)

令我惊讶的是,即使条件when为假,慢速查询仍然会执行,尽管结果从未显示并且查询毫无用处。

如何slow_query()在不需要时阻止该方法运行?

这是 Laravel 5.8 上的

mde*_*exp 5

当您调用 php 函数时,您必须在实际执行该函数之前计算传递给它的参数的值。这就是为什么您总是始终执行该slow_query()方法,即使条件为 false 时也是如此。

解决方案可能是将函数调用包装在闭包中:

class SomeResource extends Resource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'created_at' => $this->created_at,

            //The "slow_query()" should not be executed
            'slow_result' => $this->when(false, function () {
                return $this->slow_query();
            }),
        ];
    }
}
Run Code Online (Sandbox Code Playgroud)

这样,当条件为真时,您的闭包将被触发,因此执行查询并由函数->when(...)调用返回其返回值