Laravel - 如何从具有所有标准的模型中克隆

Laravel - How to clone from a model with all its criteria

我有一个包含模型的变量,我想将它及其所有条件复制到另一个变量。

$modelOne = ModelOne::where('column_one', 'value_one');

if($condition_one) {
    $modelOne = $modelOne->where('column_two', 'value_two');
}

...以及许多其他 if 条件...

$modelTwo = $modelOne;

问题从这里开始,当我将另一个 where 添加到 $modelTwo 时,$modelOne 也会受到影响。

例如,当我执行 $modelTwo->where('specific_column', 'specific_value') 时,$modelOne 将受到为 $modelTwo 设置的 where 的限制。

如何将他们的 where 分开?

您可以使用 PHP clone 关键字:

$modelOne = ModelOne::where('column_one', 'value_one');
// ...

$modelTwo = clone $modelOne;
// changes to $modelTwo should not affect $modelOne anymore

eloquent 构建器在内部实现了 __clone 魔术方法以克隆内部查询构建器