I've 2 databases and 2 models, here is the models
Category.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $guarded = [];
public function sub_categories()
{
return $this->hasMany(Category::class, 'parent_id', 'id');
}
public function products()
{
return $this->hasMany(\App\Product::class);
}
public function all_products()
{
return $this->hasManyThrough(\App\Product::class, \App\Category::class, 'parent_id', 'category_id', 'id', 'id');
}
}
Product.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public function category()
{
return $this->belongsTo(\App\Category::class);
}
}
Products table
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('category_id');
$table->string('name');
$table->string('slug')->unique();
$table->text('description');
$table->text('galleries');
$table->timestamps();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
});
Categories table
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('parent_id')->nullable();
$table->string('name');
$table->string('slug')->unique();
$table->text('description');
$table->timestamps();
$table->foreign('parent_id')->references('id')->on('categories');
});
the problem I got is, I want to get all products if the parent category is selected. So let's say I have this category and products
Category 1 <-- parent category with 3 products \
Category 1-a <-- child category with 1 products \ 13 products in total
Category 1-b <-- child category with 2 products /
Category 1-c <-- child category with 7 products /
Category 2 <-- parent category
Category 2-a <-- child category
Category 2-b <-- child category
Category 2-c <-- child category
So I created the all_products()
relationship in Category model with hasManyThrough()
, but I can't get all the products if I selected the parent category, which is only have 3 products but will show all products from it's children as well.
So how to get all the products with the eloquent way? so I can call it just by using $category->all_products()
?
Thank you