【问题标题】:Laravel 8, Creating a query builder and adding more queries to it step by step, how can one rollback step by step?Laravel 8,创建一个查询构建器并逐步向其中添加更多查询,如何逐步回滚?
【发布时间】:2022-01-05 15:29:54
【问题描述】:

在 laravel 8 中,我创建了一个简单的查询构建器。

$myRestaurants = Restaurant::where('status', 'active');
$myRestaurants->where('id', '>', 3);
$myRestaurants->where('color', 'red');

结果将是这样的 Illuminate\Database\Eloquent\Builder:

$myRestaurants = Restaurant::where('status', 'active')->where('id', '>', 3)->where('color', 'red');

首先,Laravel 将此查询添加到 $myRestaurants,我不确定这种行为是否正确。顺便说一句,我想回滚到前一步,例如:

$myRestaurants = Restaurant::where('status', 'active')->where('id', '>', 3);

【问题讨论】:

  • 您在哪里/如何自动将这些条件添加到您的查询中?
  • 查询构建器对象具有公共的$bindings$where 属性,因此理论上您可以操作这些属性。如果您不小心,您可能最终会完全破坏您的查询,但最好在实际向查询中添加内容之前防止这种需要
  • @Rwd 这很奇怪!!我从未保存过查询,只是在对象上调用它们。我不知道我错过了哪里,但是当我添加像:“$myRestaurants->where('foo', 'bar')”这样的行时,它会自动添加并保存到变量 ($myRestaurants) 中的查询生成器。
  • @apokryfos 啊哈!。现在我知道发生了什么事。但是我怎样才能绕过这个呢?
  • 我想要做的是过滤一些带电的模型。用户取消选择某些条件后,我想返回上一个查询。

标签: laravel laravel-query-builder laravel-collection


【解决方案1】:

你不需要回去试试Restaurant::query()

$myRestaurants = Restaurant::query();
if (true) { // any
    $myRestaurants->where('status', 'active');
}else if(false) {
    $myRestaurants->where('id', ">", 3);
}else if(true) {
    $myRestaurants->where('color', 'red');
}

【讨论】:

  • 谢谢。而已。我猜 'Restaurant::query()' 会重置查询生成器,对吧?它有效!
  • @ehsanmohiti 是的,它收集了所有的 sql 语句
猜你喜欢
  • 1970-01-01
  • 2013-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多