menu

Questions & Answers

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!

Comments:
2023-01-17 00:48:03
I'm confused. To use a scope you need to call get() on it, don't you?
2023-01-17 00:48:03
Of course you need to use get to return a collection, else you are basically just executing the query without returning anything
2023-01-17 00:48:03
So, I know you're confused, but it actually works perfectly. And it's so useful so you might want to use it. You're defined scoped relationships like that. See another example in that answer : stackoverflow.com/a/26178429/1928380
Answers(1) :

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.