tms157

Polymorphic many to many categories with nested related child categories

Posted 2 months ago by tms157

Hi everyone,

Iv been trying to figure out how to get polymorphic many to many categories with child to load in the categories with children that are also related to the model e.g. products with categories and child categories that have the same categorizable_id in the pivot table as the product id.

This is what i have so far, the categories relation works find as does children only when im trying to do it on a product it dose not:

class Product extends Model
{

    public function categories(): MorphToMany
      {

        return $this->morphToMany(Category::class, 'categorizable')->withTimestamps();

      }

}
class Category extends Model
{

    public function products(): MorphToMany
    {
        return $this->morphedByMany(Product::class, 'categorizable');
    }

    public function children(): HasMany
    {
        return $this->hasMany(Category::class, 'parent_id', 'id');
    }

}

Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('type');
            $table->string('context');
            $table->integer('parent_id')->nullable();
            $table->timestamps();
            $table->softDeletes();
        });


Schema::create('categorizables', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('category_id')->unsigned();
            $table->morphs('categorizable');
            $table->timestamps();
        });

Im trying all sorts but cant figure it out e.g.:

        $product->categories()->with(['children' => function($q) use ($product) {
            return $q->where(categorizable_id, $product->id);
        }])->get();

    $product->categories()->with(['children' => function($q) use ($product) {
            return $q->wherePivot('categorizable.categorizable_id', $product->id);
        }])->get();

Iv also tried lots of diffrent whereHas

Any help would be amazing!

Thanks,

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.