【问题标题】:Laravel - How to clone from a model with all its criteria [duplicate]Laravel - 如何从具有所有标准的模型中克隆 [重复]
【发布时间】:2021-06-23 23:15:51
【问题描述】:

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

$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 的限制。

我怎样才能分开他们的wheres?

【问题讨论】:

标签: php laravel model criteria


【解决方案1】:

您可以使用 PHP clone 关键字:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-27
    • 1970-01-01
    • 2013-05-05
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多