eggplantSword's avatar

Search scope in model returns 'Column in where clause is ambiguous'

I want to create a scope in the modal to run in a search I want to know if in an array of ids the products categories are included or not.

This is the code I have right now, this doesn't work at all, it doesn't make a difference

function scopeCategoryStore($query, $request, $active)
{
    if ($request['query'] && $request["query"]["active"] != 'null') {
            $query->whereHas('categories', function ($q) use ($active) {
                $q->whereIn('category_id', $active);
            });
    }
}

public function categories()
{
    return $this->belongsToMany(Category::class, 'category_product')->where('is_active', true);
}

//pivot table
 Schema::create('category_product', function (Blueprint $table) {
    $table->unsignedBigInteger('category_id');
    $table->unsignedBigInteger('product_id');
    $table->foreign('category_id')->references('id')->on('categories');
    $table->foreign('product_id')->references('id')->on('products');
});

This is in the controller

 $active_categories = [];

if ($request['query']['active'] !== null) {
    array_push($active_categories, intval($request['query']['active']));
}

$pagination = $request->query('pagination');
$prod = Product::where('is_active', true)
        ->with(['categories', 'images' => function ($query) {
            $query->where('default', true);
        }])
        ->OrderStore($request)
        ->BrandStore($request)
        ->CategoryStore($request, $active_categories)
        ->paginate($request['pagination']['per_page'], ['*'], 'page', $pagination['page']);

This is the error I get

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'category_id' in where clause is ambiguous (SQL: select count(*) as aggregate from products where is_active = 1 and exists (select * from categories inner join category_product on categories.id = category_product.category_id where products.id = category_product.product_id and category_id in (1) and is_active = 1))

How can make this scope work?

0 likes
2 replies
neilstee's avatar

@msslgomez you added a scope but you are not calling it I think?

$prod = Product::where('is_active', true)
        ->with(['categories', 'images' => function ($query) {
            $query->where('default', true);
        }])
        ->OrderStore($request)
        ->BrandStore($request)
        ->CategoryStore($request)
		->category($request) // add this
        ->paginate($request['pagination']['per_page'], ['*'], 'page', $pagination['page']);
eggplantSword's avatar

Sorry the name of the scope is actualy scopeCategoryStore I must've copied it wrong, so I am calling it

Please or to participate in this conversation.