ivanv's avatar
Level 20

Can't filter down Collections when using PHPUnit?

Hey all...

I have a product that has a many to many relation with categories. Each category belongs to a group.

In the Product model I have the relation set up:

    public function categories()
    {
        return $this->belongsToMany(ProductCategory::class, 'product_category_product', 'product_id', 'product_category_id');
    }

I wanted to get the first category within a given group that is attached to a product. So In the Product model I wrote:

    public function firstCategory($groupId)
    {
        return $this->categories->where('product_group_id', $groupId)->first();
    }

Although it works in the browser, PHPUnit never returns a result.

When I do the following, PHPUnit does return a result and works as expected... (mind categories()) but then I get way too many queries...

    public function firstCategory($groupId)
    {
        return $this->categories()->where('product_group_id', $groupId)->first();
    }

Does anyone know why this is?

I'm using Laravel 5.2.45 with PHPUnit 5 on an SQLite in-memory database (also tried with database.sqlite file).

0 likes
2 replies
ivanv's avatar
ivanv
OP
Best Answer
Level 20

Got it to work with this:

public function firstCategory($groupId)
{
    return $this->categories->first(function ($key, $category) use ($groupId) {
        return $category->product_group_id == $groupId;
    });
}

/victory :)

Please or to participate in this conversation.