1

I have a table named assignations where I store the id of the category and the id of the product assigned to this category. Like this: enter image description here

The query that I am looking for is to get all the products that are not assigned to a specific category. For example, if the category is id=1, the query would have to return the products 4, 5 and 6.

This is the code I have tried but I can't achieve what I want.

$assignations = Assignation::where('category_id', $id)->orderBy('position', 'Asc')->get();
$no_variants_assigned = Variant::whereNotIn('id', function ($query) use ($assignations) {
    $query->select('v.id')
          ->from('variants', 'v')
          ->where('v.id_product', $assignations->id);
})->orderBy('id_product', 'Asc')->get();

Please, I hope someone can help me. Thanks

2 Answers 2

1

Try this code :

$id[] = 1;

$assigns =  array_unique(Assignation::whereNotIn('category_id', $id)->pluck('product_id')->toArray());
$products = Product::whereIn('id', $assigns)->orderBy('id', 'Asc')->get();

return $products;

Edit:

Added checking the category if exists before getting data, so the code should be:

$category = Category::findOrFail($id);
$assigns =  array_unique(Assignation::where('category_id', $id)->pluck('product_id')->toArray());
$variants = Variant::whereNotIn('id', $assigns)->orderBy('id_product', 'Asc')->get();
Sign up to request clarification or add additional context in comments.

1 Comment

This is not correct because I want all products that are not assigned to a specific category, and with your first query, you are not taken into account that some products could have not been assigned to any category yet.
0

Te @Pejman Kheyri answer is not what I want, but he helps me to find the solution:

public function getCategoryVariantAssignation($id){
        $category = Category::findOrFail($id);
        $assignations = array_unique(Assignation::where('category_id', $id)->pluck('product_id')->toArray());
        $no_variants_assigned = Variant::whereNotIn('id', $assignations)->orderBy('id_product', 'Asc')->get();
        $data = ['category' => $category, 'variants' => $no_variants_assigned];
        return $data;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.