लारवेल एलक्विंट क्वेरी बिल्डर चेनिंग मूल आधार क्वेरी [डुप्लिकेट] को प्रभावित करता है

Dec 15 2020

मैं इस क्वेरी को कैसे काम कर सकता हूं?

$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.

फिर, मैं एक स्टार्टर पॉइंट के रूप में एक मूल संग्रह रख सकता हूं जिसे बाद में प्राप्त () संचालन द्वारा संशोधित नहीं किया जाएगा।

धन्यवाद!

जवाब

2 lagbox Dec 15 2020 at 01:31

यदि आपके पास एक बिल्डर है और आप बिल्डर की एक नई प्रतिलिपि चाहते हैं, तो आप एक क्वेरी बनाना जारी रख सकते हैं, जिससे आप बिल्डर को "क्लोन" कर सकते हैं:

$cloned = clone $query;

अब $clonedइसका अपना उद्देश्य है और आप $queryमूल बिल्डर पर प्रभाव डाले बिना क्वेरी का निर्माण कर सकते हैं ।

यदि आप वास्तव cloneमें बिल्डर पर एक विधि चाहते हैं और यह मौजूद नहीं है तो आप इसे स्थूल कर सकते हैं:

Illuminate\Database\Query\Builder::macro('clone', function () {
    return clone $this;
});

आप इसे सेवा प्रदाता की bootविधि में फेंक सकते हैं ।

2 Donkarnash Dec 15 2020 at 01:35

बिल्डर पर एक क्लोन विधि उपलब्ध है (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.xa मैक्रो से नीचे की लारवेल क्रियाओं को 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()
    {
        //
    }
}