how to get the list of products using a category id

Viewed 291

I have 2 tables Categories & Products:

--------------------------
-       categories       -
--------------------------
- id          | int      -
- name        | varchar  -
- category_id | int      -
--------------------------

--------------------------
-        products        -
--------------------------
- id          | int      -
- name        | varchar  -
- category_id | int      -
--------------------------

enter image description here

enter image description here

Each category may has a parent category or not, the column category_id refer to it. Each product belongs to a category.

Exp : Cat1 -> cate1.2 -> cat1.3->... -> cat1.x-> pro1

Cat2 -> pro2

I want if I search by cat1 or cate1.2 or ... or cat1.x, I can reach the pro1 without knowing all the categories, and the same for pro2??

I use for this sql or eloquent-laravel.

1 Answers

Please put these two methods in Category Model.

public function parent(){
        return $this->belongsTo(Category::class, 'category_id');
}

public function products(){
        return $this->hasMany(Product::class, 'category_id');
}

and this in Product model

public function category() {
        return $this->belongsTo( Category::class );
    }
}

and get parent category like this.

$category = Category::findOrFail(2);
dd( $category->parent );

and products of a category like this.

dd( $category->products );

and category of a product like this.

$product = Product::first();

dd( $product->category );
Related