简体   繁体   中英

Issue with HasMany definition with scope

so I'm defining this function in a Dosser model:

    public function billingDocs()
    {
        return $this->hasMany(BillingDoc::class);
    }

    public function regularInvoiceDocs()
    {
        return $this->billingDocs()->regularType();
    }

And in BillingDoc model:

    public function scopeRegularType(Builder $builder)
    {
        $builder->where('billing_type_id', BillingType::named('regular')->id);
    }

Now, if I call from a function in Dossier model $this->regularInvoiceDocs it returns an empty array. But if I call $this->regularInvoiceDocs()->get() it returns the desired items. Of course if I just call $this->billingDocs I have the desired items as well. I thought defining HasMany functions with scope conditions was fine? I use it a lot without issue, I don't understand what is happening here. Thanks ahead!

Actually I was mistaken and the issue came from another part of my code. It was a test, and the function building regularInvoiceDocs relationship was called twice, once when it's empty and the second time when it should have returned a collection. But the relationship was cached from the first time. So, a simple $dossier->refresh() and everything works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM