emeka mamah
emeka mamah

Reputation: 629

Property [columns] does not exist on the Eloquent builder instance

i'm getting this error while trying to add a subquery select to a query builder. this error occurs when i try to get the product count for a given category.

addSubSelect Macro

Builder::macro('addSubSelect', function ($column, $query) {
            if (is_null($this->columns)) {
                $this->select($this->from.'.*');
            }
            return $this->selectSub($query, $column);
        });

Category.php

public function scopeWithProductCount($query){
        $query->addSubSelect('products_count', function($query) {
            $query->whereHas('product', function ($query) {
            $query->select('id')
                ->from('products')
                ->whereColumn('category_id', 'category.id')
                ->count();
        });
        });
    }

Category Controller

public function index()
    {
        $categories = $this->user()->store->categories()
            ->withProductsSum()
            ->get();

        return response()->json($categories);
    }

here is a screenshot of the error

i changed the scopedWithProductCount method to this to try and get more debugging options but i end up with the same error

public function scopeWithProductCount($query){

    $query->addSubSelect('', function($query) {

    });
}

Upvotes: 0

Views: 3696

Answers (2)

MD.Tabish Mahfuz
MD.Tabish Mahfuz

Reputation: 666

The columns property is in the Illuminate\Database\Query\Builder Class and not Illuminate\Database\Eloquent\Builder. Your $this will refer to the Eloquent\Builder reference and not the Query\Builder.

So try changing your macro like this:

addSubSelect Macro

Builder::macro('addSubSelect', function ($column, $query) {
    if (is_null($this->getQuery()->columns)) {
            $this->select($this->from.'.*');
    }
    return $this->selectSub($query, $column);
});

Upvotes: 1

Nick
Nick

Reputation: 546

Write join and the name of the table before the field:

public function scopeWithProductCount($query){
        $query->addSubSelect('products_count', function($query) {
            $query->whereHas('product', function ($query) {
            $query->select('products.id')
                ->from('products')
                ->join('categories', 'categories.id', '=', 'products.category_id')
                ->count();
        });
    });
}

Upvotes: 0

Related Questions