Laravel条件API资源执行所有功能,即使没有必要?



所以我有一个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()),
];
}
}

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

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

这是在拉拉维尔 5.8 上

当你调用一个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();
}),
];
}
}

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

最新更新