我怎样才能让这个查询工作?
$basic_query = Invoices::between_days(15, 7); // This is a collection of invoices from 15 days ago, to seven days in the future. Notice I am not getting this query, it´s still just a builder instance. If you do dd($basic_query->get()) you get 100 invoices, 60 of them paid, 40 of them outstanding.
$paid_invoices = $basic_query->paid()->get(); // This returns the collection of 60 paid invoices without problems. BUT MODIFIES $basic query, if you dd($basic query->get()) at this point, you only get the 60 paid invoices, not the full 100 invoices collection. ¿?!!!
$outstanding_invoices = $basic_query->paid(false)->get(); // This query will always be empty, even though there are many outstanding invoices. If you dd($basic_query->get()) at this point, you get an empty collection. The 100 invoices are lost.
那么我怎样才能有一个基本集合作为起点,并且不会被后续的 get() 操作修改。
谢谢!
最佳答案
构建器上有一个可用的克隆方法(Illuminate\Database\Query\Builder) 可以使用的
$basic_query = Invoices::between_days(15, 7);
$paid_invoices = $basic_query->clone()->paid()->get();
$outstanding_invoices = $basic_query->clone()->paid(false)->get();
更新
对于低于 8.x 的 Laravel 版本,可以在 AppServiceProvider 或新的 MacroServiceProvider 启动方法中定义宏。
使用 MacroServiceProvider - 不要忘记将其添加到 config/app.php
中的提供者数组
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Query\Builder;
class MacroServiceProvider extends ServiceProvider
{
public function boot()
{
Builder::macro('clone', function() {
return clone $this;
});
}
public function register()
{
//
}
}
关于php - Laravel Eloquent Query Builder 链接影响原始基本查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65294518/