"when"语句在拉拉维尔中如何运作?



假设有这样一个代码

$users = Model::when($param, function($query) {
$query->where('id', 1)
})
->get();

"when"函数,如果存在$param参数,将调用该函数,查询将为

select * from table where id = 1

如果没有参数,则查询为

select * from table

问题是laravel如何以及在哪里收集这个动态请求。

如果有疑问,请查看源代码:https://github.com/laravel/framework/blob/6316655d0bc823854aa3397d2f21515a5eb03929/src/Illuminate/Conditionable/Traits/Conditionable.php#L21-L40

这是一种被称为Conditionable(IlluminateSupportTraitsConditionable)的性状:

public function when($value = null, callable $callback = null, callable $default = null)
{
$value = $value instanceof Closure ? $value($this) : $value;
if (func_num_args() === 0) {
return new HigherOrderWhenProxy($this);
}
if (func_num_args() === 1) {
return (new HigherOrderWhenProxy($this))->condition($value);
}
if ($value) {
return $callback($this, $value) ?? $this;
} elseif ($default) {
return $default($this, $value) ?? $this;
}
return $this;
}

这是为Laravel 10.x


因为方法when返回$this(在最后一行),它允许您执行$model->when(..., ...)->when(..., ...)->where(xxx)->first()(作为示例)。当你像上面的例子那样用方法调用时,它被称为method chaining

最新更新